简体   繁体   English

MySQL记录在同一表中没有子

[英]Mysql records with no child in same table

I need to get the messages that are childless within the same table 我需要在同一张表中获得无子的消息

ID  parent_id  body
1   NULL       my first comment (parent)
2   1          my reaction on first comment (child)
3   NULL       comment without reactions

As you can see the message are related my the parent_id. 如您所见,消息与parent_id相关。 How can I get the parents without any child related. 我该如何让没有任何孩子的父母。 So me result would be 所以我的结果是

ID  parent_id  body
3   NULL       comment without reactions

I tried some stuff but I cant figure it out. 我尝试了一些东西,但无法弄清楚。 Like select in select. 就像在选择中选择。 On stackoverflow I could find some examples but does were mostly from 2 tables, not in the same. 在stackoverflow上,我可以找到一些示例,但大多数示例来自2个表,而不是同一表。 Maybe I mist does. 也许我有雾。 Anyone can help me out? 有人可以帮我吗?

Try using a NOT EXISTS clause which asserts that a given record has no parents and has no children: 尝试使用NOT EXISTS子句,该子句断言给定记录没有父代没有子代:

SELECT *
FROM yourTable t1
WHERE
    t1.parent_id IS NULL AND
    NOT EXISTS (SELECT 1 FROM yourTable t2 WHERE t2.parent_id = t1.ID);
SELECT * FROM table1 WHERE parent_id IS NULL AND id NOT IN ( SELECT parent_id FROM table1 WHERE parent_id IS NOT NULL )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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