两个表之间的MySQL表比较

时间:2014-10-05 22:44:54

标签: mysql sql

我有两个表,followfollowed。我想获取follow表中的所有行,以便follow.screen != followed.following_screen_name

关注表格

ID    screen_name
-----------------
1      eddie
2      jason
3      omar
4      jonathan
5      jack

紧随其后的表格

ID    my_screen_name    following_screen_name
-------------------------------------------
1      john                eddie
2      kenny               eddie
3      kenny               omar
4      john                jason
5      john                omar

查询我尝试了哪些无效

SELECT follow.screen_name from follow, followed where followed.my_screen_name='john'
AND follow.screen_name != followed.following_screen_name

预期结果

ID    screen_name 
-----------------
1      jonathan      
2      jack     

3 个答案:

答案 0 :(得分:3)

你可以通过LEFT JOIN

来实现这一点
SELECT F.screen_name FROM follow F
LEFT JOIN followed FD
on F.screen_name = FD.my_screen_name
OR F.screen_name = FD.following_screen_name
WHERE FD.my_screen_name IS NULL
and FD.following_screen_name IS NULL

另一种方法是使用NOT EXISTS,获取follow中存在的所有行,并执行NOT EXISTS子句以获得所需的结果。

SELECT F.screen_name FROM follow F
WHERE NOT EXISTS
(
  SELECT 1 FROM followed FD
  WHERE F.screen_name = FD.my_screen_name
  OR F.screen_name = FD.following_screen_name
)

答案 1 :(得分:0)

有很多方法可以解决这个问题,但共同点是你需要将follow.screen_name与follow.my_screen_name和follow.following_screen__name进行比较。

一种方法是使用带有UNION的NOT IN:

select screen_name 
from follow
where screen_name not in (
  select following_screen_name
  from followed 
  where following_screen_name is not null
  union all
  select my_screen_name
  from followed 
  where my_screen_name is not null
  )

虽然这种方法清晰度很好,但它的性能可能不如使用左连接或不存在。

答案 2 :(得分:0)

获取mysql语法和逻辑的好地方是here。 但是尝试这段代码,它会选择screen_name与接下来两个查询中产生的任何内容不同的每一行:

SELECT * from follow WHERE screen_name
not in (select screen_name from followed)
AND not in (select followed_screen_name from followed);

最后两个查询看起来是这样,WHERE过滤掉所有行,屏幕名称与下面的字段相同。

my_screen_name    following_screen_name
-------------------------------------
john              eddie
kenny             eddie
kenny             omar
john              jason
john              omar