我有一个关于之间区别的问题!=在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的好友。建议的页面有23个来自用户2,24个来自用户3,56个来自用户4,33个来自用户6。用户2和用户3都建议使用第77页。不建议使用第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');