简体   繁体   English

在mysql中,如何查找未在表中的其他行中引用其ID的行?

[英]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.

相关问题 在mysql中,我如何只从一个表中获取行,而该行不链接到具有特定ID的另一表中的任何行 - In mysql how can I get only rows from one table which do not link to any rows in another table with a specific ID Mysql 其他表中未引用的行数 - Mysql Count of rows not referenced in other table MySQL查找不在其他表中的行 - MySQL find rows not in other table 如何从同一表获取基于parent_id的行以与其他行相对应 - How do I get rows to correspond to other rows based on a parent_id , all from the same table 用于查找不与其他表重叠的行的 MYSQL 查询 - MYSQL query for find rows not overlapping other table 如何使用 vb.net 在 mysql 数据库中找到每个 machine_id 的最后一行? - How do I find the last rows each machine_id in mysql database with vb.net? 在MySQL中,我怎么能找到所有“ attribute1”与特定行的“ attribute1”相同的行? - In MySQL, how can I find all rows whose `attribute1` is the same as a particular row's `attribute1`? 如何使用一行从同一mySQL表中提取其他多行 - How do I use one row to pull multiple other rows from the same mySQL table 如何查找其字符串值出现在另一个表的列中的所有行? - How can I find all rows whose string value appears in a column of another table? 如何在表中查找不在其他表中的行 - How to find rows in a table that are not in other table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM