这是一张包含product_id
及其功能
| 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
答案 0 :(得分: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_value
feature_title
为'warranty'
时feature_title
的结果为null
,max
为feature_value
feature_value
id= mapall
id=mapall2
空值和var =markers and var = markers2
将为<script>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(-34.031342, 18.577419); // default location
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.SATELLITE,
mapTypeControl: true
};
var map = new google.maps.Map(document.getElementById('mapall'),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
for( i = 0; i < markers.length; i++ ) {
lat = (markers[i].GPS1);
lng = (markers[i].GPS2);
name = (markers[i].client_address);
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
name:name,
map: map
});
google.maps.event.addListener( marker, 'click', function(e){
infowindow.setContent( this.name );
infowindow.open( map, this );
}.bind( marker ) );
}
}
</script>
。 -HTH
答案 1 :(得分: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;