MySQL - Select All Except what is in this Table

前端 未结 5 1418
青春惊慌失措
青春惊慌失措 2020-12-21 19:14

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

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

相关标签:
5条回答
  • 2020-12-21 19:28

    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);
    
    0 讨论(0)
  • 2020-12-21 19:33

    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.

    0 讨论(0)
  • 2020-12-21 19:33

    Try:

    SELECT
        i.*
    FROM
        _image i
        LEFT JOIN _user_image u ON u.image_id = i.id
    WHERE
        u.user_id != <user-id>
    
    0 讨论(0)
  • 2020-12-21 19:42
    select * from _image where id not in (select image_id from _user_image where user_id = ?)
    
    0 讨论(0)
  • 2020-12-21 19:55

    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 讨论(0)
提交回复
热议问题