【问题标题】:Query to find links that don't exist between 2 tables/queries查询以查找 2 个表/查询之间不存在的链接
【发布时间】:2014-06-11 00:48:36
【问题描述】:

我有 3 张桌子

USERS
user_id

ALERTS
alert_id

USER_ALERTS
user_id
alert_id
show_alert

我需要找出哪些用户未链接到哪些警报。
所以对于以下数据:

用户

user_id
--------
1       
2  

警报

alert_id
--------
9       
8   
7

USER_ALERTS

user_id alert_id
------- --------
1             9   
2             9   
1             8   
2             8  
1             7 

查询应该返回

user_id alert_id
------- --------
2             7 

我可以通过加入 2 个表找到未链接到任何用户的警报:

select a.alert_id, ua.alert_id, ua.user_id from alerts a 
left join 
user_alerts ua 
on    a.alert_id = ua.alert_id
where u.alert_id is null;

但我似乎无法返回未链接的用户和警报 - 我需要使用缺少的行更新链接表。

我可以加入所有 3 个表(几乎返回 user_alerts 行):

SELECT u.user_id, ua.alert_id FROM user u 
LEFT OUTER JOIN user_alerts ua on u.user_id = ua.user_id
LEFT OUTER JOIN alerts a on a.alert_id = ua.alert_id;

我可以尝试笛卡尔积方法 - 将所有用户与所有警报结合起来

 SELECT u.user_id, a.alert_id from user u, alerts a

通过警报获取所有当前用户

 SELECT ua.user_id, ua.alert_id from user_alerts ua

现在我需要第一个查询中不在第二个查询中的所有值,但不确定如何从这里到达那里。

有人有什么想法吗?

我正在使用 mySQL

【问题讨论】:

标签: mysql sql


【解决方案1】:

您关于笛卡尔积的想法是正确的。无条件加入usersalerts即可实现。查找缺少哪一对只是用left join过滤

select a.*
from (
  select user_id, alert_id
  from users
  join alerts) a
left join user_alerts b on a.user_id = b.user_id and a.alert_id = b.alert_id
where b.user_id is null;

演示:http://sqlfiddle.com/#!2/eb803/2

【讨论】:

  • 是的! thanx,举个例子,我不知道sql有一个小提琴。
猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 2020-01-02
  • 2011-04-19
相关资源
最近更新 更多