I feel like this must be a classic problem, but I can't find the answer.
I have a table Person, which has basic details describing a person. Then, I have a ParentChildRelationship table, which looks something like this:
CREATE TABLE `ParentChildRelationship` (
`ParentId` INT(10) UNSIGNED NOT NULL,
`ChildId` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY(ParentId,ChildId),
CONSTRAINT `FK_ParentRelationship`
FOREIGN KEY (`ParentId` )
REFERENCES `Person` (`idPerson` ),
CONSTRAINT `FK_ChildRelationship`
FOREIGN KEY (`ChildId` )
REFERENCES `Person` (`idPerson` )
);
I need a select query that simply returns all Person records for the Parent and all Children down the tree.
For example, with the following data:
Parent Child
1 3
1 8
2 4
3 5
3 6
6 9
4 7
Select all Person records where the ParentId = 1 OR ChildId is in the tree below ParentId of 1. This query should return the Person information (SELECT * FROM Person
...) for the following PersonId's:
1,3,8,5,6,9
I don't know if this matters, but the order of how these are returned do not matter, as I will need to order based off of something like "LastName" or something like that. In other words, the result could also have been 1,3,5,6,9,8.