Question

I have an items table and a tags table that are linked through a user_tags table. I have a query that finds all items with specific tags:

self::factory('item')
    ->join('user_tags', 'INNER')->on('items.id', '=', 'user_tags.item_id')
    ->join('tags', 'INNER')->on('user_tags.tag_id', '=', 'tags.id')
    ->where('tags.title', 'IN', $array_of_tags);

or without kohana orm:

SELECT items.*
FROM items
INNER JOIN user_tags ON items.id = user_tags.item_id
INNER JOIN tags ON user_tags.tag_id = tags.id
WHERE tags.title IN ($array_of_tags);

I would like to find all items that have no tags associated to them. How would I do this?

Was it helpful?

Solution

Simply add another where condition

SELECT 
    items.*
FROM items
LEFT JOIN user_tags ON items.id = user_tags.item_id
LEFT JOIN tags ON user_tags.tag_id = tags.id
WHERE tags.title IN ($array_of_tags)
AND user_tags.tag_id IS NULL;

OTHER TIPS

Switch your inner join to left join

SELECT items.*
FROM items
LEFT JOIN user_tags ON items.id = user_tags.item_id
LEFT JOIN tags ON user_tags.tag_id = tags.id
WHERE (tags.title IN ($array_of_tags) or tags.title is null)
and user_tags.item_Id is null.

Keep in mind SQL is not much more than set logic.

Here's a link to help explain the different type of joins.

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Try this::

SELECT items.*
FROM items
LEFT JOIN user_tags ON items.id = user_tags.item_id
LEFT JOIN tags ON user_tags.tag_id = tags.id
WHERE 
user_tags.tag_id is null 
AND tags.title IN ($array_of_tags)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top