问题
I have a MySQL database with the following tables:
items | id, item
items_tags | id, item_name, item_id, tag_name, tag_id
tags | id, tag
I'd like to allow the user to search for items with any tag or any combination of tags. Here's some example data to show what I'd like to do:
items:
id | item
-----------
1 | banana
2 | orange
3 | tomato
items_tags:
id | item_name | item_id | tag_name | tag_id
---------------------------------------------
1 | banana | 1 | yellow | 1
2 | banana | 1 | fruit | 2
3 | orange | 2 | orange | 3
4 | orange | 2 | fruit | 2
5 | tomato | 3 | red | 4
6 | tomato | 3 | vegetable| 5
tags:
id | tag
--------------
1 | yellow
2 | fruit
3 | orange
4 | red
5 | vegetable
What query could I run to only return items tagged with "yellow" and "fruit" (i.e., should return row 1 of items)?
Thanks!
UPDATE:
Here's the working answer:
SELECT *
FROM items
WHERE id IN (
SELECT item_id
FROM items_tags
WHERE tag_name IN ('yellow', 'fruit')
GROUP BY item_id
HAVING COUNT(*) = 2
)
Thanks to chetan for the help!
回答1:
if you want the item with any of the two tag then:
select distinct item_id, item_name
from items_tags
where tag_name in ('yellow', 'fruit');
if you want the item having both tag then:
select item_id, item_name
from items_tags
where tag_name id ('yellow', 'fruit')
group by item_id, item_name
having count(*) = 2;
based on your comment
select a.id, a.item
from items a, items_tags b, tags c
where a.id = b.item_id
and b.tag_id = c.id
group by id, item
having (group_concat(c.tag) like '%yellow%'
and group_concat(c.tag) like '%fruit%')
or group_concat(c.tag) = 'red';
This query gives id and item from items table. It gives item which has both yellow and fruit tag. and the items with only red tag.
if you want to get items with two tags and only two tags then use following condition in having clause
(group_concat(c.tag) like '%yellow%'
and group_concat(c.tag) like '%fruit%'
and count(*) = 2)
回答2:
Try this::
Select *, count(1) as noOfTags from
items_tags
group by item_id
having tag_name in ('yellow','fruit') and noOfTags=2
回答3:
Select *, count(1) as noOfTags from
items_tags
group by item_id
having tag_name in ('yellow','fruit') and noOfTags=2
yes noofTags here make sure that the item is tagged with all tags, and yes if you want to search for more tags you will add it between parentheses Another Thing i agree with Mark about his comment,they are useless & you can use view instead it you want to get something like that (At least save some space). Note : I can't comment yet so i posted like answer sorry.
来源:https://stackoverflow.com/questions/17519718/mysql-query-to-search-for-items-with-certain-tags