![](/img/trans.png)
[英]Mysql - Select & Group rows with A column, and B column where A.value and B.value = x and y or y and x
[英]Mysql Where Column A = X and Column B = Y and or Column B = Z
我正在尝试从数据透视表中获取一组值,其中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经验有限。
您可以使用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);
响应@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`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.