Question

Imagine 2 tables, the first one is a list of products (products), the second one a join table between products and another table (categories), called products-categories

products:

id   |  name
------------
1       Lorem 
2       Ipsum 
3       Dolor 
4       Sit 

products-categories

product_id  | categories_id
---------------------------
1             3
1             6
4             1
2             2

How to get the orphan elements, I mean the elements in no category, so in this case: 3, in a efficient way (+30k records) using MyISAM?

This is somehow like showing all rows that are not joinable, but this syntax seams weird to me...

Was it helpful?

Solution

select * from products p 
left join product_categories pc on p.id=pc.product_id 
where pc.product_id is null

will return all products in table products that are not found in product_Category. LEft join and where is very fast. 30k records is also very little, so don't worry there.

OTHER TIPS

Using SubQuery:

SELECT name FROM products 
WHERE id NOT IN (SELECT product_id FROM products-categories);

Using JOIN

SELECT name FROM products 
LEFT JOIN products_categories ON (id=product_id)
WHERE product_id IS NULL;

Better to go with join sqlfiddle demo : http://sqlfiddle.com/#!2/684c1/8

select p.id from products p left join product-categories c on p.id=c.product_id 
where c.id is NULL

I had a similar problem once i used something like following

select p.id from products p left join productscategories pc where pc.categories_id is null

-hj

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top