我对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。 用户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子句,则可以获得正确的结果。我对这两种方法之间的差异感到好奇。
谢谢您的帮助。
答案 0 :(得分:0)
我们无法传递!=中的多个值 例如:
以下脚本获取application_id不是eeff906835c9bd8f431c33c9b3f5ec6d的所有应用程序。
select * from application where application_id !='eeff906835c9bd8f431c33c9b3f5ec6d';
不要输入,我们可以在过滤期间传递多个值 例如:
select * from application where application_id not in ( 'eeff906835c9bd8f431c33c9b3f5ec6d','196ec1876359b2bf0640918648c3c8355');
答案 1 :(得分:0)
您可以尝试以下操作-在执行实际逻辑之前,我只是稍微重新排列了列
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