我想要选择用户尚未拥有的所有图像。
我有三个表:user
,image
和user_image
:
答案 0 :(得分:6)
LEFT JOIN/IS NULL
SELECT DISTINCT
i.data
FROM IMAGE i
JOIN USER_IMAGE ui ON ui.image_id = i.id
LEFT JOIN USER u ON u.id = ui.user_id
AND u.user = ?
WHERE u.id IS NULL
NOT IN
SELECT DISTINCT
i.data
FROM IMAGE i
JOIN USER_IMAGE ui ON ui.image_id = i.id
WHERE ui.user_id NOT IN (SELECT u.id
FROM USER u
WHERE u.user = ?)
NOT EXISTS
SELECT DISTINCT
i.data
FROM IMAGE i
JOIN USER_IMAGE ui ON ui.image_id = i.id
WHERE NOT EXISTS(SELECT NULL
FROM USER u
WHERE u.id = ui.user_id
AND u.user = ?)
LEFT JOIN/IS NULL
和NOT IN
提供相同的效果 - NOT EXISTS
效率低约30%。 See this for more details
答案 1 :(得分:0)
您可以使用子查询轻松完成此操作:
SELECT * FROM image WHERE id NOT IN
(SELECT image_id FROM user_image WHERE user_id = THE_USER_ID);
答案 2 :(得分:0)
select * from _image where id not in (select image_id from _user_image where user_id = ?)
答案 3 :(得分:0)
尝试:
SELECT
i.*
FROM
_image i
LEFT JOIN _user_image u ON u.image_id = i.id
WHERE
u.user_id != <user-id>
答案 4 :(得分:0)
从id不在的图像中选择id,日期(从user_image中选择image_id,其中user_id =
有一种更快捷的方法,但这更容易理解。
另一种方式是:
select user,data from data left user user_image on user.id = user_image.user_id where user_image.id = null