CREATE TEMPORARY TABLE pairs (
	taxId1 INT(10) unsigned NOT NULL,
	taxId2 INT(10) unsigned NOT NULL,
	nDistance1 INT(10) unsigned NOT NULL,	
	nDistance2 INT(10) unsigned NOT NULL,	
	UNIQUE combined(taxId1,taxId2) );

INSERT pairs (taxId1, taxId2, nDistance1, nDistance2)
	SELECT t1.childId taxId1, t2.childId taxId2,
			MIN(t1.nDistance) nDistance1, MIN(t2.nDistance) nDistance2
		FROM TaxParentChild t1,TaxParentChild t2
		WHERE t1.parentId=t2.parentId
		GROUP BY taxId1,taxId2 HAVING nDistance1=MIN(t1.nDistance);

SELECT pairs.taxId1 taxId1, pairs.taxId2 taxId2, tt2.parentId parentId,
	n1.name name1, n2.name name2, n3.name parentName,
	pairs.nDistance1 nDistance1, pairs.nDistance2 nDistance2, tt3.nDistance nToTop
	FROM pairs, TaxParentChild tt2, TaxParentChild tt3, Taxonomy n1, Taxonomy n2, TaxName n3
	WHERE tt2.childId=pairs.taxId1 AND tt2.nDistance=pairs.nDistance1
		AND n1.taxonomyId=pairs.taxId1
		AND n2.taxonomyId=pairs.taxId2
		AND n3.taxonomyId=tt2.parentId AND n3.class='scientific name'
		AND tt3.parentId=1 AND tt3.childId=tt2.parentId
	ORDER BY taxId1, taxId2;
DROP TABLE pairs;
