2017-10-08 228 views
-1

這是一個包含product_id S和它們的功能表SQL選擇記錄

| product_id | feature_title | feature_value | 
+------------+---------------+---------------+ 
| 6312 | warranty |  1  | 
| 6312 |  color  |  red  | 
| 2083 | warranty |  1  | 
| 2083 |  color  |  blue  | 
| 8686 | warranty |  0  | 
| 8686 |  color  |  red  | 

如何選擇,只有這些細節記錄:

warranty = 1 
color = red 

回答

2

我想你需要像這樣:

select * 
from (
    select product_id 
     ,max(case when feature_title = 'warranty' then feature_value end) warranty 
     ,max(case when feature_title = 'color' then feature_value end) color 
    from yourTable 
    group by product_id   -- grouping to one row per id 
    ) pivot 
where 
    warranty = '1' and 
    color = 'red'; 

My SQL Fiddle Demo
SQL Server Fiddle Demo

當我想比較同一ID的多個記錄,我更喜歡那些分組記錄一排像旋轉工作臺,用於旋轉數據的方法是使用max(case)以上在內部選擇的顯示。
對於case when feature_title = 'warranty' then feature_value end示例結果將是feature_valuefeature_title'warranty'和用於其它feature_title的IT將null零點所以maxfeature_valuefeature_value。 -HTH

+0

感謝。它在MySQL上工作嗎? – AliN11

+0

@ AliN11是[它會生效](http://www.sqlfiddle.com/#!9/63f30/4);)。 –

+0

謝謝。它的工作,但我不明白這個查詢 真是可怕的查詢 – AliN11

2

我只想做到這一點使用聚合:

select product_id 
from t 
group by product_id 
having sum(case when feature_title = 'warranty' and feature_value = '1' then 1 else 0 end) > 0 and 
     sum(case when feature_title = 'color' and feature_value = 'red' then 1 else 0 end) > 0; 

首先,不是所有的數據庫都支持pivot。其次,我不認爲子查詢增加了很多查詢。

注:也許一個簡單的版本是:

select product_id 
from t 
where (feature_title = 'warranty' and feature_value = '1') or 
     (feature_title = 'color' and feature_value = 'red') 
group by product_id 
having count(distinct feature_title) = 2; 
+0

謝謝。這也適用 – AliN11