从这个Mysql表:
Attributes
Brand |attr | vals
Samsung | RAM | '750'
Samsung | CPU | '1200'
HTC | RAM | '1000'
HTC | CPU | '1500'
我不知道如何使用
获取所有项目RAM>500
CPU>1300
结果我只需要符合所有参数的品牌:
Attributes
Brand |attr | vals
HTC | * | *
看看SQL小提琴: http://sqlfiddle.com/#!2/491d7/1
答案 0 :(得分:4)
我会通过旋转数据获得结果:
select brand, RAM, CPU
from
(
select brand,
max(case when attr='RAM' then cast(vals as unsigned) end) as RAM,
max(case when attr='CPU' then cast(vals as unsigned) end) as CPU
from attributes
group by brand
) d
where RAM > 500
and CPU > 1300
答案 1 :(得分:2)
最外面的WHERE子句首先限定1300或更多的RAM属性。通过同一品牌再次加入自己(别名“b”),你现在拥有相同的品牌,但这次你只是在CPU上限定“b”属性,它的值> = 500.你可以保持链接任何其他标准的其他JOIN。这是在你正在寻找的所有组件上进行限定...
select
a.Brand,
a.vals as RAM,
b.vals as CPU
from
Attributes a
JOIN Attributes b
on a.Brand = b.Brand
AND b.attr = 'CPU'
AND b.vals >= 1300
where
a.attr = 'RAM'
AND a.vals >= 500
答案 2 :(得分:1)
SELECT
Brand
FROM Attributes
WHERE
(attr = 'RAM' AND cast(vals as unsigned) > 500)
OR (attr = 'CPU' AND cast(vals as unsigned) > 1300)
GROUP BY Brand
HAVING COUNT(*) >= 2
答案 3 :(得分:1)
更改@ bluefeet的查询,因此没有派生表。它可能会提高某些MySQL版本的效率,但它会破坏ANSI / ISO SQL的有效性,并且不会以ONLY_FULL_GROUP_BY
模式运行:
select brand,
max(case when attr='RAM' then cast(vals as unsigned) end) as RAM,
max(case when attr='CPU' then cast(vals as unsigned) end) as CPU
from attributes
group by brand
having RAM > 500
and CPU > 1300 ;
改进它,所以它也是有效的:
select brand,
max(case when attr='RAM' then cast(vals as unsigned) end) as RAM,
max(case when attr='CPU' then cast(vals as unsigned) end) as CPU
from attributes
group by brand
having max(case when attr='RAM' then cast(vals as unsigned) end) > 500
and max(case when attr='CPU' then cast(vals as unsigned) end) > 1300 ;