0

我有 mySQL 数据库:

CREATE TABLE `inventory` (
  `id` int(11) NOT NULL auto_increment,
  `device` int(11) NOT NULL,
  `property` varchar(40) NOT NULL,
  `value` varchar(200));

包含以下数据:

1, 1, 'code', '123'
2, 2, 'code', '12345'
3, 1, 'old_code', '987'
4, 3, 'code', '12345'
5, 2, 'old_code', '12345'

我需要获取 'code'<>'old_code' 的设备列表。我认为这应该是可行的,但我的想法无法绕过它。

4

3 回答 3

3

你可以这样做:

SELECT 
  device
FROM
(
   SELECT 
     device,
     MAX(CASE WHEN property = 'code'     THEN value ELSE NULL END) AS Code,
     MAX(CASE WHEN property = 'old_code' THEN value ELSE NULL END) AS old_code
   FROM inventory
   GROUP BY device
) AS t
WHERE code <> old_code;
于 2013-10-08T12:47:38.343 回答
3

使用自联接:

SELECT   new.device
FROM     inventory AS new 
    JOIN inventory AS old
      ON old.device = new.device
     AND old.property = 'old_code'
     AND new.property = 'code'
WHERE    new.value <> old.value

sqlfiddle上查看。

于 2013-10-08T12:50:25.213 回答
0

尝试自我加入

select a.* from inventory as a join inventory as b on a.device=b.device 
where a.property='code'
and b.property='old_code' and a.value!=b.value
于 2013-10-08T12:51:07.250 回答