Php Mysql,其中列A=X,列B=Y,或列B=Z

Php Mysql,其中列A=X,列B=Y,或列B=Z,php,mysql,sql,relational-database,rdbms,Php,Mysql,Sql,Relational Database,Rdbms,我试图从一个透视表中获取一组值,其中a列等于一个值数组,因此例如ID12的属性_value_ID等于3和9。这能做到吗?我已经走了这么远 ID | post_id | attribute_id | attribute_value_id 8 12 1 3 9 12 2 13 10 13 1 3 11 13 2

我试图从一个透视表中获取一组值,其中a列等于一个值数组,因此例如ID12的属性_value_ID等于3和9。这能做到吗?我已经走了这么远

ID | post_id | attribute_id | attribute_value_id
8      12          1             3
9      12          2            13
10     13          1             3
11     13          2             9
12     16          1             3
13     16          2             9
88     11          1             1
89     11          2             8
90     11          3            18
91     11          4            22
查询

select * 
from `searching_for_posts` 
where (
    select count(*) 
    from `attributes` 
    inner join `searching_for_attributes`
    on `attributes`.`id` = `searching_for_attributes`.`attribute_id` 
    where `searching_for_attributes`.`searching_for_post_id` = `searching_for_posts`.`id` 
    and (`attribute_value_id` = 3 and `attribute_value_id` = 9)
) >= 1

如果使用
,则不会得到任何值。如果我使用
则得到3个值,但它应该返回2。我的SQL经验有限。

您可以使用
groupby
have
来实现这一点。你的逻辑很难理解,但它是这样的:

select post_id
from table t
where attribute_value_id in (3, 9)
group by post_id
having count(distinct attribute_id) = 2;
我想您也应该检查一下
属性\u id
,但这似乎不是问题的一部分

编辑:

如果这些存储在另一个表中:

select a.post_id
from attributes a join
     searching_for_attributes sfa
     on a.attribute_id = sfa.attribute_id and
        a.attribute_value_id = sfa.attribute_value_id
group by a.post_id
having count(*) = (select count(*) from searching_for_attributes);

作为对@GordonLinoff答案的回应,我已经设法使用GROUP BY和have COUNT来获得所需的数据。这是我想到的,希望这能帮助其他人

select * 
from `searching_for_posts`
where (
    select count(*) 
    from `attributes` 
    inner join `searching_for_attributes` on `attributes`.`id` = `searching_for_attributes`.`attribute_id` 
    where `searching_for_attributes`.`searching_for_post_id` = `searching_for_posts`.`id` 
    and `attribute_value_id` in (3, 9)
    having count(distinct `attributes`.`id`) = 2
) >= 1
group by `id`

(`attribute\u value\u id`=3和`attribute\u value\u id`=9)
在逻辑上是不可能的<代码>属性值id不能同时将
3
9
作为其值,你的意思可能是
(`attribute\u value\u id`=3或`attribute\u value\u id`=9)
。。。。或者你的意思是(3,9)中的
(`attribute\u value\u id`)
@MarkBaker不,如果有人搜索某个产品,并且他们想要所有的产品都是蓝色的,并且都有内置的CD播放机,我想得到这样的数据。所有属性数据都在透视表中,每个项目都有自己的行。这可能是个问题。请让我知道这是否足够清楚。1.查看您的数据。只有一行ID为12.输入错误?2.这是什么表格?另一个表格的数据是什么?感谢您的深入回复。我从您的第一次回复中获得了灵感,使用了分组方式和计数方法。再次感谢。