Re: SQL query: looking for NON-intersection of tables

From: Conal Tuohy <Conal.Tuohy_at_nyob>
Date: Fri, 26 Jan 2007 10:14:19 +1300
To: CODE4LIB_at_listserv.nd.edu
Ken Irwin wrote:

> Hi folks,
>
> I'm trying to put together a MySQL query to do something I don't know
> how to do: get a list of materials that DON'T show up in a
> relational table.
>
> For example, 3 tables:
>
> 1) lib.books : lots of bib data including book_id
> 2) lib.subjects: subj_code, selector, subject_name
> 3) relational: lists book_id & subj_code
>
> I want to generate a list of books that are in lib.books that doesn't
> have any subjects assigned to it.
>
> I could do this with 2 queries, but it gets unwieldy: get a list of
> distinct book_ids and AND/NOT them all together like:
> SELECT * FROM books WHERE book_id != '4' and book_id != '7'...
> That works on really small sets, but I don't want to go that route.
>
> Is there a savvy way to structure this MySQL query. I don't even know
> the language to use to look for this information.

Try this:

SELECT *
FROM books
WHERE NOT EXISTS(
        SELECT *
        FROM relational
        WHERE relational.book_id = books.book_id
)

Cheers

Con
Received on Thu Jan 25 2007 - 15:13:05 EST