MySQL - 选择全部除了此表中的内容

时间:2010-01-21 01:44:22

标签: sql mysql

我想要选择用户尚未拥有的所有图像。

我有三个表:userimageuser_image

  • _user(id,user,pass)
  • _image(id,data)
  • _user_image(id,user_id,image_id)

5 个答案:

答案 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 NULLNOT 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