tags:

views:

88

answers:

6

I have two tables

ITEMS : id, name

CATEGORIES: items_id, category

I need to select all the items whose IDs are NOT in the CATEGORIES table.

I suspect it's really simple, but can't figure out the syntax.

A: 

This selects everything from the items table and only the records from categories that match the join. Then filter out the nulls.

Select Item.Id
FROM ITEMS LEFT OUTER JOIN CATEGORIES On
Items.Id = Categories.items_id
where categories.items_id is null
Mike Pone
MySQL fields are not case sensitive. The code is really sloppy though, so I approve your downvote.
Artem Russakovskii
+1, I like the left join method over the NOT IN
KM
+3  A: 

try this:

SELECT
    i.*
    FROM Items   i
        LEFT OUTER JOIN Categories  c ON i.id=c.items_id
        WHERE c.items_id is NULL
KM
+3  A: 

NOT IN (select CATEGORIES.item_id)

not sure if that's faster than the join above... but it works.

Dr.Dredel
That's how I would do it too and it's a lot simpler.
Artem Russakovskii
If the performance is important ... Profile both versions. That said, my first (and likely only) swing at it would be with the NOT IN.
Adrien
I prefer the use the LEFT JOIN over the NOT IN, because in the past I've been burned with the query not using the index and plain joins usually use the indexes properly. I'm not familiar enough with mysql to know which will run faster, but if the both use the index they will be the exact same execution plan.
KM
A: 

How about

SELECT id
, name
FROM ITEMS
WHERE NOT EXISTS(SELECT 1 FROM CATEGORIES WHERE Categories.items.id = ITEMS.id)

This will only bring back items that do not have at least one entry in the Categories table

James Conigliaro
A: 
SELECT items.id
  FROM items
 WHERE NOT EXISTS( SELECT *
                     FROM categories
                    WHERE items.id = categories.items.id )

This is the same as joining to the categories table as Mike Pone and KM listed but I find this more readable.

Paul Morgan
+2  A: 
SELECT * FROM Items
WHERE id NOT IN (SELECT items_id FROM Categories)
Joe Philllips