mysql - 检查是否存在多个关系的最有效方法
问题描述
假设我需要找到所有文章,这些文章都标有三个标签food
:lifestyle
和health
。在 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
推荐阅读
- java - ExectuorService 和 CompletableFuture 的关系
- php - PHP检查字符串是否包含括号
- vue.js - 无效的道具:道具“背景” elementui el-pagination 的类型检查失败
- python - 使用 PyDub 时出错。我该如何解决?
- git - Git 执行 pull 而不提交或存储或重置不会受到影响的本地更改
- swift - Xcode 错误,似乎没有有效的解决方案/修复(编译器无法在合理的时间内对该表达式进行类型检查)
- python - 为什么 Python Pandas 中的 Read_HTML 不起作用?
- html - 为什么 bootstrap4 的汉堡图标不显示小屏幕的菜单?
- mysql - 如何在 MySQL 中将字符串列作为列表读取?
- php - 下拉列表未访问 WordPress 子目录数据库中的类别项目