PHP-一个查询中的SQL筛选器类别

时间:2018-06-28 18:38:24

标签: php mysql sql

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

Category_relationships就像

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

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

我想用一个SQL查询列出文章编号3。
我该怎么办?

对不起,我的英语:)

1 个答案:

答案 0 :(得分:0)

可能有多种方法来获得理想的结果,以下查询基于匹配条件,即文章是否具有这两个类别,如果有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
)