Search code examples
sqlsql-serverrelational-division

Need help coming up with query to find something that is in everything


Ok, I am working with the publishers database and the query that I need to come up with is to find the title of any book that has sold copies in every store.

The main tables that I am dealing with are title, sales and store

Here is my attempt

  SELECT title, titles.title_id, stores.stor_id, sales.stor_id, stor_name
    from titles
     FULL OUTER JOIN sales on sales.title_id = titles.title_id
    FULL OUTER JOIN stores on stores.stor_id = sales.stor_id
    --WHERE sales.stor_id = stores.stor_id AND sales.title_id = titles.title_id

I have an idea what I should do. I need to join titles.title_id to sales.title_id annd then check to see if sales.stor_name is equal to stores.stor_name


Solution

  • Try this:

    select t1.title from titles t1
    where t1.title_id not in (
      select sub.title_id from sales sa
      right join (
        select t.title_id, stor_id from titles t, stores st
      ) Sub on sa.title_id = sub.title_id and sa.stor_id = sub.stor_id
      where sa.title_id is null)
    

    Example