假设我需要查找所有用三个标签标记的文章:foodlifestylehealth。在MySQL中最有效的方法是什么?我想出了这个解决方案:

select * from articles
where exists (
    select * from tags
    join article_tag on article_tag.tag_id = tags.id
    where article_tag.article_id = articles.id
    and tags.tag = 'food'
) and exists (
    select * from tags
    join article_tag on article_tag.tag_id = tags.id
    where article_tag.article_id = articles.id
    and tags.tag = 'lifestyle'
) and exists (
    select * from tags
    join article_tag on article_tag.tag_id = tags.id
    where article_tag.article_id = articles.id
    and tags.tag = 'health'
)


它工作正常,但看起来很重复。解决此问题的最有效查询是什么?

最佳答案

select a.*
from articles a
join (
select articles.id
from articles
join article_tag on article_tag.article_id = articles.id
join tags on article_tag.tag_id = tags.id
where tags.tag in ('food','lifestyle','health')
group by articles.id
having SUM(CASE WHEN tags.tag = 'food' THEN 1 ELSE 0 END) >= 1
AND SUM(CASE WHEN tags.tag = 'lifestyle' THEN 1 ELSE 0 END) >= 1
AND SUM(CASE WHEN tags.tag = 'health' THEN 1 ELSE 0 END) >= 1) b on a.id = b.id

关于mysql - 检查是否存在多个关系的最有效方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56684663/

10-10 21:01
查看更多