2014-06-11 30 views
0

我有3個表查詢發現,沒有2個表之間存在的聯繫/查詢

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

+0

我希望這個問題將會給你一些想法。 http://stackoverflow.com/questions/13502068/get-the-opposite-results-from-a-select-query – user3720852

回答

2

您對笛卡爾產品的想法是正確的。無需任何條件即可加入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

+0

是的! thanx,指出例子,我不知道有一個sql的小提琴。 – gebuh