gpt4 book ai didi

mysql - 使用 NOT IN 且子选择返回 NULL 时的查询问题

转载 作者:行者123 更新时间:2023-11-29 07:46:06 25 4
gpt4 key购买 nike

我正在尝试找出这里做错了什么。基本上,下面的查询查询表“Profilest1,然后再次使用 NOT IN 函数查询同一个表“Profiles”并从中获取 profile_friends t2 并显示在 t2 结果中找不到的 ID 的结果。

查询

SELECT t1.profile_id,  t1.profile_username, t1.profile_name, t1.profile_friends 
FROM PROFILES t1
WHERE t1.profile_id NOT IN (SELECT t2.profile_friends FROM PROFILES AS t2 WHERE t2.profile_id = '1')

上述查询和数据库结构的结果 enter image description here

此 ID 的 2,6,10 不应显示在此结果中。那么 ID 2 未显示,但为什么显示 ID 610

但是当我尝试这段代码时它可以工作(请注意,我已经对值进行了硬编码)

SELECT t1.profile_id,  t1.profile_username, t1.profile_name, t1.profile_friends 
FROM PROFILES t1
WHERE t1.profile_id NOT IN (2,6,10)

最佳答案

您必须考虑NULL。任何与 NULL 的常见比较(=、<>、>、<)都会得到 NULLNULL 的正确比较是 IS NULL

此外,您的情况似乎不需要子查询。

SELECT *
FROM profiles
WHERE profile_id <> 1
AND (profile_friends <> '1' OR profile_friends IS NULL) -- parentheses are important here

示例输出:

| PROFILE_ID | PROFILE_USERNAME | PROFILE_FRIENDS ||------------|------------------|-----------------||          3 |        username3 |          (null) ||          4 |        username4 |          (null) ||          5 |        username5 |          (null) ||          7 |        username7 |          (null) ||          8 |        username8 |          (null) ||          9 |        username9 |          (null) |

这是一个 SQLFiddle 演示

关于mysql - 使用 NOT IN 且子选择返回 NULL 时的查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757951/

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