php - PHP - 一次查询中的 SQL 过滤器类别
问题描述
我的数据库中有 3 个表Categories
:Category_relationships
和Article
.
Category_relationships
就好像
id | category | article
---+----------+--------
1 | 2 | 3
2 | 4 | 3
我得到一个这样的网址:filter.php?category[]=2&category[]=4
我想用一个 SQL 查询列出第 3 篇文章。
我怎样才能做到这一点?
对不起我的英语:)
解决方案
可能有多种方法可以获得所需的结果,以下查询基于匹配文章是否具有这 2 个类别,如果有 3 个类别并且您需要应用匹配条件 3 次,每次匹配具有不同的类别 ID
使用聚合
select a.id, a.name
from article a
join category_relationships cr on a.id = cr.article_id
join category c on c.id = cr.category_id
group by a.id, a.name
having count(case when c.id = 2 then 1 else null) > 0
and count(case when c.id = 4 then 1 else null) > 0
或者
select a.id, a.name
from article a
join category_relationships cr on a.id = cr.article_id
join category c on c.id = cr.category_id
where c.id in(2,4)
group by a.id, a.name
having count(c.id) = 2
这里 2 是可变的,取决于要匹配的类别数量,此外,如果有可能出现重复,例如每篇文章有多个具有相同类别 ID 的条目,则使用 count(distinct c.id) = 2
使用 EXISTS
select a.id, a.name
from article a
where exists(
select 1
from category_relationships
where a.id = article_id
and category_id = 2
) and exists(
select 1
from category_relationships
where a.id = article_id
and category_id = 4
)
推荐阅读
- jquery - Jquery TR 可排序,用于单独的手风琴
- c# - 如何使用 C# 网络服务?
- forms - 为什么“toFillForm”在 jest-puppeteer 中不起作用?
- kubernetes - Kubernetes 主节点未接收到内部 IP
- java - 如何在快速 android 网络库中的参数中发送数组
- jenkins - archiveArtifacts finger print = false 是什么意思?
- python - lambda 函数的布尔值可以为 false 吗?
- office-js - Office Add in 可以通过添加来自不同于窗口密钥库的外部源的数字签名来修改电子邮件吗?
- android - 删除后在 Google Play 上更新 Android 应用
- c# - 我无法在 Internet 断开连接下控制 Chrome Selenium Web 驱动程序 [WebDriver 异常]