之间的区别!=而不是在mysql环境中

xurqigkl  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(304)

我有一个关于!=而不是在mysql环境中。原始问题如下:
表:友谊

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user1_id      | int     |
| user2_id      | int     |
+---------------+---------+

(user1\u id,user2\u id)是此表的主键。此表的每一行都表示user1\u id和user2\u id之间存在友谊关系。
表:喜欢

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| page_id     | int     |
+-------------+---------+

(user\u id,page\u id)是此表的主键。此表的每一行都表示用户\ id喜欢页\ id。
编写一个sql查询,使用您的朋友喜欢的页面向user\u 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个来自用户3,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子句,我可以得到正确的结果。我很好奇这两种方法之间的区别。
谢谢你的帮助。

li9yvcax

li9yvcax1#

您可以尝试下面的方法—在执行实际逻辑之前,我只是稍微重新排列一下列

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

jk9hmnmh

jk9hmnmh2#

我们不能在中传递多个值!=例如:
下面的脚本获取应用程序id不是eeff906835c9bd8f431c33c9b3f5ec6d的所有应用程序。

select * from application where application_id  !='eeff906835c9bd8f431c33c9b3f5ec6d';

在筛选过程中,我们可以传递多个值,例如:

select * from application where application_id  not in ( 'eeff906835c9bd8f431c33c9b3f5ec6d','196ec1876359b2bf0640918648c3c8355');

相关问题