2017-10-08 120 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