简体   繁体   中英

How do I compare values from different column and different row but same table?

ID Name FatherID Birthyear

1   Bart    NULL     1756    
2   Franz   1        1796
3   Josef   2        1835    
4   Zohan   3        1887

Suppose I have this table, I would like to know if Zohan is the son of Bart, which can be gotten if I compare the values from the column "FatherID" with the ID of the previous rows up until I get to Bart. But how do I compare the values in the same table but of different rows and columns

You could self join the table:

SELECT s.name AS son_name, f.name AS father_name
FROM   mytable s
JOIN   mytable f ON s.fatherID = f.id
-- possibly add a where clause with conditions on son/father names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM