Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Geschwister-Datensätze in einer MySQL-Closure-Tabelle finden

Die Geschwister eines gegebenen Knotens teilen sich denselben Vorfahren. Allerdings würde das auch „1“ neben deine beabsichtigte Liste aufnehmen:

select t.* from table t where t.ancestor = (select ancestor from table t2 where t.id = 2); 

In deiner Tabelle bin ich nicht sicher, was es bedeutet, wenn ancestor gleich descendant ist, aber ich denke, das kommt dem näher, was du willst:

select t.* from table t where t.ancestor = (select ancestor from table t2 where t2.id = 2) and t.ancestor <> t.descendant and t.id <> 2; 

BEARBEITUNG:

Du kannst dies auch als expliziten Join ausdrücken:

select t.* from table t join table t2 on t.ancestor = t2.ancestor and t2.id = 2 a where t.id <> 2 and t.ancestor <> t.descendant; 

Beachte, dass ich auch t.id <> 2 hinzugefügt habe, damit „2“ nicht als sein eigenes Geschwister gezählt wird.