Mysql其中列A = X且列B = Y和/或列B = Z.

时间:2015-07-11 11:24:36

标签: php mysql sql relational-database rdbms

我正在尝试从数据透视表中获取一组值,其中A列等于值数组,因此例如ID 12的attribute_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

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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`