Question

I have two related tables. One of the tables contains every entry for the photos and the other has all the cat entries for each photo and user info.

photos table:
id
photo (unique filename)
user


cats tables

photo
user
cat

photos

1    photo1.jpg    40000
2    photo2.jpg    40000
3    photo3.jpg    40000
4    photo4.jpg    40001
5    photo5.jpg    40001

cats

photo1.jpg    40000    A
photo2.jpg    40000    A
photo1.jpg    40000    B
photo1.jpg    40000    C
photo2.jpg    40000    P
photo3.jpg    40000    A

Each photo can be assigned to more categories for every user

What i want is to select all photos for user 40000 that have not been included in 'P' cat even if they may have been included in 'A', or 'B' cat.

Because photo2.jpg is included in P cat should not appear in the search results. My query for user 40000 should give the folowing results:

photo1
photo3
Was it helpful?

Solution

Should be a simple left-join / null test

select
      p.id,
      p.photo
   from
      photos p
         left join cats c
            on p.photo = c.photo
            AND c.cat = 'P'
   where
          p.user = 40000
      and c.photo is null

Basically, the left join still allows all photos to be qualified. However, if the join specifically DOES exist in the categories table by the same photo AND category = 'P', then it will have a value for the "c.photo". So in the where clause, I've added to only include those that DO NOT (via null) exist in the cat table.

OTHER TIPS

mysql> select * from photos 
       where photo not in (select photo from cats where cat='P') 
       and user = '40000';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top