Mysql
 sql >> Database >  >> RDS >> Mysql

MySQL:seleziona tutti gli elementi con più hashtag

bene conosci la tua lista, quindi è una semplice stringa. e conosci il tuo conteggio. questi possono essere bloccati in un Prepared Statement di mysql ed eseguito.

Ma di seguito è con l'elenco e il conteggio inseriti solo a scopo dimostrativo.

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)