当实际值不为0

时间:2017-05-27 00:06:07

标签: mysql sql

表:

CREATE TABLE `test_table` (
  `id` int(10) UNSIGNED NOT NULL,
  `field` varchar(255) COLLATE utf8_swedish_ci NOT NULL,
  `value` text COLLATE utf8_swedish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;

INSERT INTO `test_table` (`id`, `field`, `value`) VALUES
(1, 'first_name', '0'),
(2, 'last_name', '0'),
(3, 'first_name', '1'),
(4, 'last_name', '1');

查询:

SELECT MAX(`id`), `field`, `value` FROM test_table GROUP BY `field`

据我所知,这应该返回具有更高id的每个字段的值。

但它正在回归:

MAX(`id`)    field          value
3            first_name     0
4            last_name      0

它返回正确的id,正确的字段但错误的值。这里发生了什么,如何修复它以返回第3行和第4行?

1 个答案:

答案 0 :(得分:1)

SELECT t.`id`, t.`field`, t.`value` 
FROM test_table t
JOIN (SELECT MAX(`id`) AS `id`, `field` 
      FROM test_table 
      GROUP BY `field`) t1 ON t1.`id` = t.`id`