首页 > 解决方案 > 检查是否存在多个关系的最有效方法

问题描述

假设我需要找到所有文章,这些文章都标有三个标签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'
)

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

标签: mysqlsqlrelational-database

解决方案


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

推荐阅读