tags:

views:

70

answers:

5

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

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

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

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);
pib
Would upvote if i could. I'm at the daily limit.You could also do instead of `NOT`, in the subquery write `!=`.
Jacob Relkin
A: 
select * from _image where id not in (select image_id from _user_image where user_id = ?)
Kaleb Brasee
A: 

Try:

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

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

Martin
+5  A: 

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.

OMG Ponies
I would have thought left join beats not in. Good point!
Martin
The `LEFT JOIN/IS NULL` can be done with one less join and without `DISTINCT`. Have a peek at my solution.
Vadim K.