I have the following nested table:
CREATE TABLE personal2 (
emp VARCHAR(20) PRIMARY KEY,
salary DECIMAL(6,2) NOT NULL,
lft INTEGER NOT NULL UNIQUE CHECK (lft > 0),
rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1)
);
ALTER TABLE personal2 ADD CONSTRAINT orderOKAY
CHECK (lft < rgt);
INSERT INTO personal2 VALUES('Albert', 1000, 1, 16);
INSERT INTO personal2 VALUES('Bert', 900, 2, 3);
INSERT INTO personal2 VALUES('Chuck', 900, 6, 15);
INSERT INTO personal2 VALUES('Donna', 800, 9, 10);
INSERT INTO personal2 VALUES('Eddie', 700, 11, 12);
INSERT INTO personal2 VALUES('Fred', 600, 13, 14);
INSERT INTO personal2 VALUES('Gilbert', 900, 4, 5);
INSERT INTO personal2 VALUES('Hans', 850, 7, 8);
Now I am supposed to get the pairs of child and their parents, which apparently should work like this and indeed gives the correct result:
SELECT a.emp, b.emp
FROM personal2 a, personal2 b
WHERE (SELECT COUNT(*)
FROM personal2 c WHERE a.lft BETWEEN c.lft and c.rgt
AND c.lft Between b.lft AND b.rgt) = 2;
I am not able to understand this query completely and I also don't get why this works. So apparently I am creating the cartesian product of the table in the beginning. And now I am selecting specific rows from it, which are defined in the subquery. But I don't understand what happens there and why this makes me leaving with child-parent pairs. Can somebody explain this to me?