解釋這個問題的最好方式是通過它所要解決的現實生活的例子。 我有兩個表,匹配概述和匹配屬性
。匹配概述看起來像
id, home_id, away_id, date, result。
同時匹配的屬性看起來像
id, match_id, attribute_id, attribute_value
其中match_id是match overview表中id的外鍵,屬性id是屬性的整數表示,例如,
home_goals_full_time or total_yellow_cards or away_goals_extra_time
我想對比賽屬性進行查詢,找到所有總進球數大于X的比賽。
由于每個屬性都是一個獨立的行,我們需要找到所有屬性ID為{3,4,5,6}的行,如果3和4(home_goals_full_time away_goals_full_time)之和大于X或者5和6(home_goals_extra_time away_goals_extra_time)之和大于X,我們就回傳匹配的id。
一個解決方案是在我的比賽概覽表中添加一個總進球數列并進行搜索,但是我希望能夠對我的任何屬性進行搜索,而我的屬性有很多,而且不是每場比賽都有一個屬性,如果我在我的比賽概覽表中為每個屬性添加一個列,那么這個表就會非常寬,而且充滿空值。
是否有可能做一個查詢,讓我輸入一個值X,然后回傳所有屬性之和大于(或小于)X的游戲? 或者這需要多個查詢或可能需要重新設計我的模式。
uj5u.com熱心網友回復:
這是很直接的:
這是很直接的。
select m.id
from match_overview m
join match_attributes ma on ma.match_id=m.id andma. attribute_id in (3,4, 5, 6)
group by m.id
having sum(case when ma. attribute_id in (3,4) then ma.attribute_valueend) > X
or sum(case when Ma. attribute_id in (5,6) then ma.attribute_valueend) > X
uj5u.com熱心網友回復:
這個任務的另一個簡單的查詢:
select *
from match_overview m
where
(
select sum(ma.attribute_value)
from match_attributes ma
where ma.match_id = m.id
and ma.attribute_id in (3, 4)
) > @ X
or
(
select sum(ma.attribute_value)
from match_attributes ma
where ma.match_id = m.id
and ma.attribute_id in (5,6)
) > @X;
還有一個:
select *
from match_overview m
where id in
(
select match_id
from match_attributes
where attribute_id in (3, 4)
group by match_id
having sum(attribute_value) >/span> @X
)
or id in
(
select match_id
from match_attributes
where attribute_id in (5, 6)
group by match_id
having sum(attribute_value) >/span> @X
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/321956.html
標籤:
上一篇:SQL。如何用計數來劃分列?
