MYSQL,如果存在
MYSQL, where if exists
我有 3 个 table。用户、警报和首选项。用户显然是我的用户信息table。 Alert 是我的 table 存储用户 alert/notification 设置的地方,pref 是我存储用户首选项的地方。
并非所有用户都有首选项和警报条目。当我尝试拨打警报时,我 运行 因我的 SQL 知识而陷入困境。
我正在尝试对 user、alert 和 pref 进行 3 种方式加入,其中 uid 相同。我想 Select 所有 user.id 并忽略所有具有 alert.deleted 和 pref.deleted = 1
的 uid
user | alert | pref
id uid uid
alert_id pref_id
deleted deleted
一种方法是
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);
但是如果你想说你想要所有真正有警报和偏好的用户,而不是那些被删除的用户,你可以使用
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;
任你选。
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)
;
我有 3 个 table。用户、警报和首选项。用户显然是我的用户信息table。 Alert 是我的 table 存储用户 alert/notification 设置的地方,pref 是我存储用户首选项的地方。
并非所有用户都有首选项和警报条目。当我尝试拨打警报时,我 运行 因我的 SQL 知识而陷入困境。
我正在尝试对 user、alert 和 pref 进行 3 种方式加入,其中 uid 相同。我想 Select 所有 user.id 并忽略所有具有 alert.deleted 和 pref.deleted = 1
的 uid user | alert | pref
id uid uid
alert_id pref_id
deleted deleted
一种方法是
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);
但是如果你想说你想要所有真正有警报和偏好的用户,而不是那些被删除的用户,你可以使用
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;
任你选。
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)
;