tags:

views:

165

answers:

1

I have four MYSQL 5.0 tables: userdb, filterdb, filterlinkdb, mandatoryfilterdb.

All tables are simple. * = pri

userdb:
 id*
 name

filterdb:
 id*
 name

filterlinkdb:
 user_id*
 filter_id*

mandatoryfilterdb
 filter_id*

How can I check filterlinkdb to make sure that all mandatoryfilterdb records exist for every user_id using a single (with or without subs) query?

Edit :: I forgot to say, I would like to return the filter_id values from mandatorydb that are not present in filterlinkdb for all user_id, eg: user #1 only has filter 1, but 1 and 2 are in the mandatorydb, so it would return user 1, filter 2 (as that is missing).

+1  A: 

That should work:

select userdb.id,mandatoryfilterdb.filter_id
from userdb 
  join mandatryfilterdb 
  on 1
    left join filterlinkdb
    on userdb.id=filterlinkdb.user_id 
      and mandatryfilterdb.filter_id=filterlinkdb.filter_id 
where filterlinkdb.user_id is null

It selects all the cartesian multiple between users and mandatory-filters, and check them against the true filterlinkdb table. If they aren't there (filterlinkdb.user_id is null, you can check the filter_id instead, it's the same) - than give them in the result of the query.

If none record returned - you are consistent.

Y. Shoham
Thank you very much, I'm reading over it to understand it better. I don't think I would have been able to write that query myself. Again, Thanks.
Majin Magu