简体   繁体   中英

In mysql how do I find rows whose id are not referenced in any other rows in the table?

My table has three columns

ID   parent_ID   item

As you can understand, it's for a nested menu. Now I need to find those elements which don't have any child elements. In other words, whose id isn't being used as parent_ID for any other rows( and order them by item ). Can I do this with a mysql query?

SELECT * FROM mytable m WHERE NOT EXISTS (SELECT 1 FROM mytable m2 WHERE m2.parent_ID = m.ID)

I would use a LEFT JOIN instead of a subquery:

SELECT Parents.* FROM mytable Parents
LEFT JOIN mytable Childs ON Parents.ID = Childs.parent_ID
WHERE Childs.ID IS NULL

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