MySQL连接3个表并在一个表中找到“缺失”行

时间:2016-04-21 12:12:38

标签: mysql join not-exists

我在MySQL中有3个表,我需要查找用户没有特定小部件的所有实例。

示例:

Users
tenant_id user_id user_name
1         1       Bob
1         2       Fred
1         3       John
1         4       Tom

Widgets
tenant_id widget_id widget_name
1         1         Red
1         2         Blue
1         3         Green
1         4         Black

Usage
tenant_id user_id widget_id
1         1       1
1         1       2 
1         1       4
1         2       2
1         2       3
1         2       4
1         3       1
1         3       2
1         3       3
1         3       4
1         4       1
1         4       2
1         4       3

Missing in table three are:
user_name widget_name
Bob       Green
Fred      Red
Tom       Black

我尝试使用的查询是:

SELECT
  user_name, widget_name
FROM
  users left join widgets on users.tenant_id=widgets.tenant_id
WHERE 
  NOT EXISTS (
    SELECT 1 FROM usage WHERE user_id = users.user_id AND widget_id = widgets.widget_id
  ) and users.tenant_id=1

当查询完成时,它会返回一个巨大的用户名和小部件名称列表,但比我预期的要多几百个。

我不确定连接是否错误,或者我是否需要对结果进行某种分组?

3 个答案:

答案 0 :(得分:1)

这种查询背后的想法。首先生成用户和小部件的所有可能组合。然后筛选出存在的那些:

select u.user_name, w.widget_name
from users u join
     widgets w
     on u.tenant_id = w.tenant_id
where not exists (select 1
                  from usage us
                  where us.user_id = u.user_id and us.widget_id = w.widget_id and
                        us.tenant_id = u.tenant_id
                 ) and
      u.tenant_id = 1;

我认为您的逻辑缺少tenant_id表中的usage。但是,我不确定这会产生很大的不同。

答案 1 :(得分:1)

您可以使用笛卡尔积和一些内连接

select b.user_name, c.widget_name 
from 
( select u.user_id, w.widget_id
from Users as u, Widgets as w
where (u.user_id, w.widget_id) not in (select user_id, widget_id 
                                          from Usage)) as a
inner join Users as b on a.user_id = b.user_id 
inner join Widgets as c on a.widget_id = c.widget_id;

答案 2 :(得分:0)

尝试下面的一个,为我工作。

select w.widget_name, u.user_name 
from widgets w join users u on w.tenant_id = u.tenant_id
where (w.widget_name, u.user_name ) not in 
             (select w.widget_name, u.user_name
              from widgets w join `usage` us on us.widget_id = w.widget_id
              join users u on u.user_id = us.user_id);