I have a table in a MySQL database which relates items and tags, with columns item_id, tag_id
. I need to write a query which receives a list of items and a list of tags and applies each tag to each item.
My current implementation looks like this:
INSERT INTO item_tag (item_id, tag_id)
(SELECT tag.tag_id, item.item_id FROM tag, item
WHERE tag.tag_id in (:tags)
AND item.item_id in (:items))
And this works but it's hacky and inneficient, I'm querying the tag
and item
tables to fetch values I already have in the parameters (and I already know at this point those are valid ids, so I don't really need to check for existence).
Is there a cleaner way to do this? For example I think of something like (psuedo code):
SELECT * FROM all_values_in_a_column(:tags)
JOIN all_values_in_a_column(:items)