2015-07-11 90 views
1

我试图从数据透视表中获取一组值,其中列A等于值的数组,因此例如ID 12有attribute_value_id等于3和9.可以这样做吗?如果我使用and然后我没有得到任何值我走了这么远......Mysql其中列A = X和列B = Y和或列B = Z

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 

。如果我使用or那么我得到3个值,但它应该返回2.我有有限的SQL体验。

+0

'(\'attribute_value_id \'= 3 \'attribute_value_id \'= 9)'是逻辑上是不可能....'attribute_value_id'不能同时拥有'3'和'9'作为它的值,你是不是指''(\'attribute_value_id \'= 3或'attribute_value_id \'= 9)....或者你意思是'(\'attribute_value_id \'IN(3,9)' –

+0

@MarkBaker不,我想要的是获得像这样的数据,如果有人搜索一个产品,他们希望所有产品是蓝色的,并有内置的CD播放器,所有的属性数据都在一个数据透视表中,每个项目都有自己的行,这可能是一个问题,让我知道这是否足够清晰 –

+0

1.看看你的数据。 ID 12. Typo?2.这是什么表? at是另一个表的数据? – philipxy

回答

1

您可以使用group byhaving来做到这一点。你的逻辑是难以遵循,但它是这样的:

select post_id 
from table t 
where attribute_value_id in (3, 9) 
group by post_id 
having count(distinct attribute_id) = 2; 

我想你会想检查attribute_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); 
+0

感谢您的深入响应。我从使用GROUP BY和HAVING COUNT方法的第一个响应中获得灵感。再次感谢。 –

0

针对@GordonLinoff答案,我已经成功地使用GROUP BY和HAVING 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` 
相关问题