Mysql
 sql >> Datenbank >  >> RDS >> Mysql

MySQL - Wählen Sie alle Elemente mit mehreren Hashtags aus

Nun, Sie kennen Ihre Liste, das ist also eine einfache Zeichenfolge. und du kennst deine Zählung. diese können in ein mysql Prepared Statement gepackt werden und hingerichtet.

Aber darunter ist die Liste und die Anzahl nur zu Demozwecken eingefügt.

create table items
(   id int not null
);

create table tags
(   id int not null,
    name varchar(50)
);

create table item_tags
(   iid int not null,
    tid int not null
);

insert items (id) values (1),(2),(3),(4);
insert tags(id,name) values (1,'cat'),(2,'animal'),(3,'has nose');
-- note, everything has a nose so far:
insert item_tags (iid,tid) values (1,1),(1,3),(2,1),(2,3),(3,2),(3,3),(4,1),(4,2),(4,3);

select i.id,count(i.id)
from items i
join item_tags junc
on junc.iid=i.id
join tags t
on t.id=junc.tid and t.name in ('cat','animal')
group by i.id
having count(i.id)=2

-- only item 4 has both cat and animal (note nose is irrelevant)