首页 > 解决方案 > PHP - 一次查询中的 SQL 过滤器类别

问题描述

我的数据库中有 3 个表CategoriesCategory_relationshipsArticle.

Category_relationships就好像

id | category | article
---+----------+--------
1  |     2    |   3
2  |     4    |   3

我得到一个这样的网址:filter.php?category[]=2&category[]=4

我想用一个 SQL 查询列出第 3 篇文章。
我怎样才能做到这一点?

对不起我的英语:)

标签: phpmysqlsql

解决方案


可能有多种方法可以获得所需的结果,以下查询基于匹配文章是否具有这 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
)

推荐阅读