[英]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
). 换句话说,其ID是不被用作PARENT_ID任何其他行(和由命令他们item
)。 Can I do this with a mysql query? 我可以使用mysql查询吗?
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: 我将使用LEFT JOIN而不是子查询:
SELECT Parents.* FROM mytable Parents
LEFT JOIN mytable Childs ON Parents.ID = Childs.parent_ID
WHERE Childs.ID IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.