0

从这个 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

4

4 回答 4

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

请参阅带有演示的 SQL Fiddle

于 2013-04-03T21:01:22.017 回答
2

最外面的 WHERE 子句首先符合 1300 或更多的 RAM 属性。通过同一品牌再次加入自身(别名“b”),您现在拥有相同的品牌,但这次您仅在 CPU 上额外限定了“b”属性,其值 >= 500。您可以继续链接附加加入任何其他条件。这是对您正在寻找的所有组件进行限定...

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
于 2013-04-03T21:14:45.923 回答
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
于 2013-04-03T20:46:22.777 回答
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 ;
于 2013-04-03T21:32:12.913 回答