我在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


查询完成后,它会带回大量的用户名和小部件名称,但比我期望的多数百个。

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

最佳答案

这是这种查询背后的想法。首先生成用户和窗口小部件的所有可能组合。然后过滤掉存在的那些:

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。但是,我不确定这会有很大的不同。

关于mysql - MySQL联接3个表并在一个表中查找“缺失”行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36769241/

10-12 22:39