简体   繁体   中英

Select rows with reference to other rows in same table

I have a table foo with the following structure:

| id | docId  | content | parentId |
|----|--------|---------|----------|
| 1  | 19     | ...     | NULL     |
| 2  | 20     | ...     | NULL     |
| 3  | 20     | ...     | NULL     |
| 4  | NULL   | ...     | 3        |
| 5  | 20     | ...     | NULL     |
| 6  | NULL   | ...     | 5        |
| 7  | 21     | ...     | NULL     |
| 8  | NULL   | ...     | 7        |
| 9  | NULL   | ...     | 7        |

I want to select everything with docId = 20 , or with a parentId which corresponds to a row with docId = 20 .

I thought I'd get there using a LEFT JOIN but no luck:

SELECT * FROM foo a
LEFT JOIN foo b ON b.id = a.parentId
WHERE a.docId = 20

This returns all the rows where docId = 20 but not the ones where docId = NULL and a parentId is a row with docId 20.

you can try a union

SELECT * FROM foo a
LEFT JOIN foo b ON b.id = a.parentId
WHERE a.docId = 20    
UNION 
SELECT * FROM foo
WHERE docId = 20

I think you have mistake in your join rule,
I believe you have to use a.id = b.parentId not b.id = a.parentId , like:

SELECT * FROM foo a
LEFT JOIN foo b ON a.id = b.parentId
WHERE a.docId = 20

I solved it using a subquery instead of a JOIN:

SELECT * FROM foo
WHERE parentId IN (SELECT id FROM foo WHERE docId = 20)
OR docId = 20

I think

    SELECT * 
    FROM foo
    WHERE docId = 20
    UNION
    SELECT b.* 
    FROM foo a
    JOIN foo b ON a.id = b.parentId
    WHERE a.docId = 20

answers your question about parents, if you want grandparents and other ancestors, you may want to consider recursive CTEs.

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-2024 STACKOOM.COM