一个查询中的PHP-SQL筛选器类别
我的数据库中有3个表:一个查询中的PHP-SQL筛选器类别,php,mysql,sql,Php,Mysql,Sql,我的数据库中有3个表:类别,类别关系和文章 类别关系类似 id | category | article ---+----------+-------- 1 | 2 | 3 2 | 4 | 3 我得到的url是这样的:filter.php?category[]=2和category[]=4 我想用一个SQL查询列出第3篇文章。 我该怎么做 对不起,我的英文是:)可能有多种方法来获得所需的结果,下面的查询是基于匹配的,如果文章有这2个类别,如果有3个类别,
类别
,类别关系
和文章
类别关系
类似
id | category | article
---+----------+--------
1 | 2 | 3
2 | 4 | 3
我得到的url是这样的: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
或
这里2是可变的,这取决于要匹配的类别的数量,同样,如果存在重复的可能性,例如每个文章有多个条目具有相同的类别id,则使用having count(distinct c.id)=2
使用存在
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
)
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
)