mysql - grouping results taking the first in an ordered subquery

37 Views Asked by At

In mysql, I'm having trouble pulling a single row for each foreign_id based on the largest value. Strangely, different versions of mysql works (listed below)

id  foreign_id  value
---------------------
1   1           1000
2   1           2000
3   2           2000
4   2           1000
5   3           2000

I try to pull ids 2,3,5 not 1,3,5

CREATE TABLE `docs` (
  `id` int(11) NOT NULL,
  `foreign_id` int(6) DEFAULT NULL,
  `value` int(8) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `docs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `foreign_id_index` (`foreign_id`);

INSERT INTO `docs` (`id`, `foreign_id`, `value`) VALUES
(1, 1, 1000), (2, 1, 2000), (3, 2, 2000), (4, 2, 1000), (5, 3, 2000)


select 
  docs.id, docs.foreign_id, docs.value 
FROM docs
INNER JOIN
  (select id, max(value) from docs group by foreign_id) sub
  ON sub.id = docs.id
# expected results are ids (2,3,5), not (1,3,5)
1

There are 1 best solutions below

0
On

It's simpler than it looks

SELECT D.id, D.foreign_id, max_vals.max_val as value
FROM docs D
JOIN
   (SELECT foreign_id, MAX(value) as max_val
    FROM docs
    GROUP BY foreign_id) max_vals
ON D.foreign_id=max_vals.foreign_id and D.value=max_vals.max_val

In this case, you need JOIN and not INNER JOIN

There is a difficult case where there are 2 or more foreign_ids with the same MAX value...