1

Table:

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');

Query:

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

To my understand this should return the value of each fields with the higher id.

But it's returning:

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

It's returning the correct id, the correct fields but the wrong values. What's going on here and how can I fix it to return rows 3 and 4?

sleepless_in_seattle
  • 2,132
  • 4
  • 24
  • 35

1 Answers1

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`
z m
  • 1,493
  • 2
  • 19
  • 21