MYSQL,如果存在的话

时间:2015-05-25 16:06:54

标签: mysql if-statement exists

我有3张桌子。用户,警报和优先。用户显然是我的用户信息表。警报是我的表格,我存储用户警报/通知设置,而pref是我存储用户偏好的地方。

并非所有用户都会有prefs和alert的条目。当我试图打电话给我的警报时,我的SQL知识就遇到了麻烦。

我正在尝试在用户,警报和pref上进行3方式连接,其中uid是相同的。我想选择所有user.id并忽略所有具有alert.deleted和pref.deleted = 1的uid

    user    |    alert    |    pref
id           uid           uid
             alert_id      pref_id
             deleted       deleted

2 个答案:

答案 0 :(得分:2)

一种方法是

SELECT id
FROM   user
WHERE  user.id not in (SELECT uid FROM alert WHERE deleted = 1)
AND    user.id not in (SELECT uid FROM pref WHERE deleted = 1);

但是如果你想说你想要所有实际拥有警报和pref的用户,而不是那些被删除的用户,你可以使用

SELECT     id
FROM       user
INNER JOIN pref
ON         user.id = pref.uid
AND        pref.deleted = 0
INNER JOIN alert
ON         user.id = alert.uid
AND        alert.deleted = 0;

在您的问题中,您正在谈论获取警报,因此可能没有针对特定用户的任何预设,但您确实需要所有尚未删除的警报,然后使用

SELECT          id
FROM            user
LEFT OUTER JOIN pref
ON              user.id = pref.uid
AND             pref.deleted = 0
INNER JOIN      alert
ON              user.id = alert.uid
AND             alert.deleted = 0;

选择。

答案 1 :(得分:1)

SELECT id
FROM user u
WHERE NOT EXISTS (SELECT 1 FROM alert WHERE uid = u.id AND deleted = 1)
  AND NOT EXISTS (SELECT 1 FROM pref WHERE uid = u.id AND deleted = 1)
;