gpt4 book ai didi

mysql - sql:不使用并且不选择任何内容

转载 作者:行者123 更新时间:2023-11-29 01:35:20 25 4
gpt4 key购买 nike

表“树”:

+----+------+
| id | p_id |
+----+------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
+----+------+

并且这些代码没有选择任何内容。为什么?

select id,'Leaf' as type
from tree
where id not in (select distinct p_id from tree)

虽然这些工作正常,但在相同条件下使用两次

SELECT
id, 'Leaf' AS Type
FROM
tree
WHERE
id NOT IN (SELECT DISTINCT
p_id
FROM
tree
WHERE
p_id IS NOT NULL)
AND p_id IS NOT NULL

最佳答案

不要对子查询使用 NOT IN。正如 Jarlh 在评论中所说,当 any 值为 NULL 时,根本不会返回任何行。

相反,习惯于 NOT EXISTS:

select t.id, 'Leaf' as type
from tree t
where not exists (select 1 from tree t2 where t2.p_id = t.id);

这就像您期望的那样。

尽管您可以在子查询中使用WHERE t2.p_id IS NOT NULL 来解决问题,但您也可以使用NOT EXISTS。在未来的某个时间点,您会发现自己在调试另一个 NOT IN,您在其中遗漏了 WHERE 子句。

关于mysql - sql:不使用并且不选择任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com