Selecting an item matching multiple tags

我只是一个虾纸丫 提交于 2019-11-30 04:46:46

问题


This seems very basic but I can't figure it out.

I've got a table "item_tags", and I want to select all of the items that match tags 1 and 2 (as in, each item has to have both tags).

How would I do this in mysql?

Create table is:

CREATE TABLE `item_tags` (
  `uid_local` int(11) NOT NULL DEFAULT '0',
  `uid_foreign` int(11) NOT NULL DEFAULT '0',
  `sorting` int(11) NOT NULL DEFAULT '0',
  KEY `uid_local` (`uid_local`),
  KEY `uid_foreign` (`uid_foreign`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Thanks!


回答1:


Use:

  SELECT i.uid
    FROM ITEMS i
    JOIN ITEM_TAGS it ON it.uid_local = i.uid
                   AND it.uid_foreign IN (1, 2)
GROUP BY i.uid
  HAVING COUNT(DISTINCT it.uid_foreign) = 2

You need to have a GROUP BY and HAVING clause defined, and the count of distinct tag ids must equal the number of tags you specify in the IN clause.




回答2:


something like this?

SELECT i.* from items i inner join items_tags it
on i.id = it.item_id
inner join tags t
on t.id = it.tag_id
WHERE t.name in ('tag1', 'tag2');

EDIT:

suppouse you have items_tags: (item_id, tag_id) as table



来源:https://stackoverflow.com/questions/3119840/selecting-an-item-matching-multiple-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!