[英]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.