我有一个关于 MySQL 环境中 != 和 NOT IN 之间区别的问题。原问题如下:
表:友谊
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user1_id | int |
| user2_id | int |
+---------------+---------+
(user1_id, user2_id) 是该表的主键。 该表的每一行都表示user1_id和user2_id之间存在好友关系。
表:喜欢
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| page_id | int |
+-------------+---------+
(user_id, page_id) 是该表的主键。 该表的每一行都表示 user_id 喜欢 page_id。
编写一条 SQL 查询,使用您朋友喜欢的页面向 user_id = 1 的用户推荐页面。它不应该推荐您已经喜欢的页面。
以任意顺序返回结果表,不重复。
查询结果格式如下例:
友情表:
+----------+----------+
| user1_id | user2_id |
+----------+----------+
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
| 6 | 1 |
+----------+----------+
喜欢表:
+---------+---------+
| user_id | page_id |
+---------+---------+
| 1 | 88 |
| 2 | 23 |
| 3 | 24 |
| 4 | 56 |
| 5 | 11 |
| 6 | 33 |
| 2 | 77 |
| 3 | 77 |
| 6 | 88 |
+---------+---------+
结果表:
+------------------+
| recommended_page |
+------------------+
| 23 |
| 24 |
| 56 |
| 33 |
| 77 |
+------------------+
用户 1 是用户 2、3、4 和 6 的好友。 建议的页面包括来自用户 2 的 23 个页面、来自用户 3 的 24 个页面、来自用户 3 的 56 个页面和来自用户 6 的 33 个页面。 第 77 页是由用户 2 和用户 3 推荐的。 不建议第 88 页,因为用户 1 已经喜欢它了。
我的做法是:
# Write your MySQL query statement below
select distinct
page_id as 'recommended_page'
from likes
where user_id in (
(select
user2_id as user_id
from friendship
where user1_id = 1)
union
(select
user1_id as user_id
from friendship
where user2_id = 1)
) and page_id <> (
select
page_id
from likes
where user_id = 1
)
但是我将收到 NULL 作为以下测试用例的结果:
{"headers":{"Friendship":["user1_id","user2_id"],
"Likes":["user_id","page_id"]},
"rows":{"Friendship":[[1,3],[1,5],[1,6],[2,3],[3,5],[3,9],[4,6],[5,9],[8,9]],
"Likes":[[6,13],[8,10],[9,14]]}}
如果我切换到IN子句,我可以获得正确的结果。我很好奇这两种方法之间的区别。
谢谢您的帮助。
您可以尝试以下操作 - 其中我只是在执行实际逻辑之前稍微重新排列列
with crt as(
select
case when
id_2 = id_col then id_q
else id_2 end as id_q_final, id_col
from
(select *,
case when
id_q > id_2 then id_q
else
id_2
end as id_col
from friendship) T)
select distinct(page_id) from
likes
inner join
crt on
crt.id_col = likes.id
where crt.id_q_final = 1 and page_id not in (select page_id from likes where id=1);
测试用例将会产生
13
我们不能在 != 中传递多个值 例如:
以下脚本获取所有application_id不为eeff906835c9bd8f431c33c9b3f5ec6d的应用程序。
select * from application where application_id !='eeff906835c9bd8f431c33c9b3f5ec6d';
NOT IN 我们可以在过滤期间传递多个值 例如:
select * from application where application_id not in ( 'eeff906835c9bd8f431c33c9b3f5ec6d','196ec1876359b2bf0640918648c3c8355');
我也有同样的疑问!有谁知道为什么吗?