I have tables tags and items and a third table tagitem that matches tags to items. Users can go to the item page which gets populated with a list of tags. Upon clicking on the tag, a row is inserted in the tagitem table, tagging the item.
To prevent users from applying the same tag to an item twice, I’d like the list of tags that comes up to exclude any already applied to the item. So I think the query that pulls the tags should have a condition in it that excludes tags already assigned to a given item. However, I am having trouble doing this.
Tables are:
tags
id|tag
items
id|item
tagitem
id|tagid|itemid
A query that pulls all the tags would just be:
"SELECT * FROM tags"
Since the table with the info on tags matched to items is tagitem, I have joined them. I need to figure out how to include a condition roughly described in parentheses below that excludes any tag that has an entry in the tagitem table for the item in question.
SELECT t.*,ti.*
FROM `tags` t
LEFT JOIN `tagitem` ti
on t.id = ti.tagid
WHERE
ti.tagid NOT IN (SELECT * FROM tagitem WHERE itemid = '22')
GROUP BY t.id
This is as far as I’ve gotten. (Right now I’m getting some wierd operand error.) Would appreciate any suggestions on proper way to do this. Thanks!
One way to do it is by altering the table and adding CONSTRAINT on the table to have unique tag per item,
But if you only what do it in your query, try this one below
from your query above, when using
NOT IN(orIN), the subquery should only return one column,