Get the master parent node id for a node reference field
If you are looking for a DB query within a custom module, you could do something like the following example function that recursively goes through the reference tree to get to the top for a node.
It will work for N levels, (but not for multi-valued references or nodes with multiple node reference fields).

function mymodule_getTopReference($nid){
    $top_nid = 0;
    //load the node
    $node = node_load($nid);
    //get all reference fields
    $node_reference_fields = array();
    $field_infos = field_info_instances('node',$node-&gt;type);
    foreach ($field_infos as $field_name=&gt;$value){
        $field = field_info_field($field_name);
        if (($field['type'] == 'node_reference')){
            if ($field_value = field_get_items('node',$node,$field['field_name'])){
                $top_nid = $field_value[0]['nid'];
                break;
            }
        }
    }

    if ($top_nid &amp;&amp; ($parent_nid = mymodule_getTopReference($top_nid))){
        $top_nid = $parent_nid;
    }
    return $top_nid;
}


For example, if your node reference field was called "my_reference" and your example nodes had the following nids:


A = 1
B = 2
C = 3


and your references are as you said:


B->A (2->1)
C->B (3->2)


Then for node 'C'(3) you'd call this function like so:

$top_nid = mymodule_getTopReference(3);


which then would set $top_nid to 1 (A's nid).