我正在尝试从数据透视表中获取一组值,其中 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
如果我使用 和
则我得不到任何值。如果我使用 或
,那么我会得到 3 个值,但它应该返回 2。我的 SQL 经验有限。
最佳答案
您可以使用 group by
和 having
来做到这一点。你的逻辑很难理解,但它是这样的:
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);
关于php - Mysql Where Column A = X and Column B = Y and or Column B = Z,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356675/