mysql - Get result with matching all search queries -
i have 3 tables: comics
, tags
, comictags
.
comics
table id connected through foreign key comictags
table while tags
table id connected comictags
table through tagid
.
comics table +----+ | id | +----+ | 1 | | 2 | +----+ comictags table +---------+-------+ | comicid | tagid | +---------+-------+ | 1 | 1 | | 2 | 1 | | 2 | 2 | +---------+-------+ tags table +----+-------+ | id | tag | +----+-------+ | 1 | tag1 | | 2 | tag2 | +----+-------+
what i'd achieve is, if i'm searching tag1 , tag2 i'd comic id 2 result. given string 2 tag names.
select c.id `tags` `t` left join comictags ct on ct.tagid=t.id left join comics c on c.id=ct.comicid ((t.tag 'tag1') or (t.tag 'tag2')) group c.id
with statement i'm getting comic id 1 not want. changing or , doesn't work in statement i've created.
could point me in right direction on how comic ids match tag ids?
you need search rows tag_id 1 of tags looking for, , ensure number of rows returned equal number of tags, this:
select c.id comics c join comictags ct on ct.comicid = c.id join tags t on t.id = ct.tagid , t.tag in ('tag1', 'tag2') group c.id having count(*) = 2;
i have changed condition use in
operator. current query not have wildcards, assume looking tags exact match, in case query little nicer.
here sql fiddle example.
note if it's possible comic aligned tag more once, may want change query count(distinct t.id)
ensure number of unique tags matches. here sql fiddle example shows repeated tags not being returned current query, distinct added.
Comments
Post a Comment