Getting the right TID with 2 parents I'm trying to develop an script to upgrade nodes with a term reference.

But my source has 3 columns (copy to an in a db table) to the term tree, example:

fieldnames: ref1, ref2, ref3
fields: CAR -> REDCAR -> DARKRED

I can't use term name because it has is duplicates on the tree. Example:
fields: CAR -> REDCAR -> DARKRED
fields: BIKE -> REDBIKE -> DARKRED

How to get the right TID and verifying the tree with my DB table?
Darvanen, shs code didn't help, the module has always the correct tid, but I have to find it in a tree. 

So I made my own function. (note I'm not a php pro)
TABLE
CAT1|CAT2|CAT3

function getcorrecttid() {

$nodes = db_query('SELECT cat1, cat2, cat3 FROM {TABLE});

// record loop
foreach($nodes as $node) {

// get TID with the last column
$query = new EntityFieldQuery;
$result = $query
  -&gt;entityCondition('entity_type', 'taxonomy_term')
  -&gt;propertyCondition('name', $node-&gt;cat3)
  -&gt;propertyCondition('vid', 3)
  -&gt;execute();

// check if has more than one
if (count($result['taxonomy_term']) &gt; 1 ) {
  $tids = array();
  $tids = $result['taxonomy_term'];
  $i = 0;
  foreach ($tids as $t) {
    $Keys = array_keys($tids);

    $parent = taxonomy_get_parents($Keys[$i]);
    $pKeys = array_keys($parent);
    $c = 0;
    foreach ($pKeys as $b) {
      $pnum = array_keys($parent);
      if ($parent[$pnum[$c]]-&gt;name == $node-&gt;cat2) {
        $root = taxonomy_get_parents($pKeys[$c]);
        $rKeys = array_keys($root);
        $a = 0;
        foreach ($rKeys as $z) {
          // found a correct TID after a lot of loops, (caution this is a heavy, heavy search.....)
          $mytid = $Keys[$i];
          }
        $a++; 
        }
      }
      $c++;
    }
    $i++;
  }    
} else {
  $mytid = array_shift($result['taxonomy_term'])-&gt;tid;
  // Found no multi parents...
}
}
}