[英]How to Select * FROM table1, table2 correctly when table1 = table2
有一個表cs_goods_features是這樣的(id-產品id,f-產品屬性名,v-屬性值)
ID | F | v |
---|---|---|
1個 | f1 | 10 |
1個 | f2 | 15 |
1個 | f3 | 25 |
2個 | f1 | 10 |
2個 | f2 | 15 |
2個 | f3 | 35 |
3個 | f1 | 15 |
3個 | f2 | 10 |
3個 | f3 | 55 |
我只需要 select 那些產品 ID,例如,f1 = 10 和 f2 = 15。
如果我這樣查詢
SELECT id
FROM cs_goods_features
where (f in ('f1', 'f2'))
and (v in (10,15))
那么一切都很好,除非表格具有相反的值 - 不是 f1=10 和 f2=15,而是 f1=15 和 f2=10。 結果集中不需要這樣的行。
我需要的可以這樣做:
select g1.id, g2.id
FROM cs_goods_features g1, cs_goods_features g2
WHERE g1.f = 'f1'
and g1.v = 10
and g2.f = 'f2'
and g2.v = 15
但這里的問題是我在 output 中得到兩列(如果我需要 select 產品的 3 個屬性 - 會有 3 列)。 我對此並不滿意,因為實際上這個查詢將成為更大查詢中的子查詢。
換句話說會有
SELECT *
FROM tablename
where ID in (our_query)
這意味着我只需要一列包含構造“where ID in (...)”的結果才能正常工作
一種方法是為每個id
計算 (f1, 10) 和 (f2, 15) 出現的次數,並在它們至少出現一次的地方選擇distinct id
:
select distinct id from
(select *,
sum(case when f = 'f1' and v = 10 then 1 else 0 end) over(partition by id) as f1_10,
sum(case when f = 'f2' and v = 15 then 1 else 0 end) over(partition by id) as f2_15
from cs_goods_features) t
where f1_10 > 0 and f2_15 > 0
我想你只是分成兩組,如下所示:
SELECT id
FROM cs_goods_features
WHERE (f = 'f1' AND v = 10)
OR (f = 'f2' AND v = 15)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.