开发者

MySQL - Select All Except what is in this Table

I am wanting to select all images that a user does not already have.

I have three tables: user, image, and user_image:


Using 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

Using 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 = ?)

Using 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 = ?)

Performance:


The LEFT JOIN/IS NULL and NOT IN provide equivalent performance - the NOT EXISTS is ~30% less efficient. See this for more details.


You can do it pretty easily with a subquery:

SELECT * FROM image WHERE id NOT IN 
    (SELECT image_id FROM user_image WHERE user_id = THE_USER_ID);


select * from _image where id not in (select image_id from _user_image where user_id = ?)


Try:

SELECT
    i.*
FROM
    _image i
    LEFT JOIN _user_image u ON u.image_id = i.id
WHERE
    u.user_id != <user-id>


select id, date from image where id not in (select image_id from user_image where user_id =

There is a faster way but this is easier to follow.

Another way would be:

select id, data from image left join user_image on user.id=user_image.user_id where user_image.id = null

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜