简体   繁体   English

mysql-将结果分组到有序子查询中的第一个

[英]mysql - grouping results taking the first in an ordered subquery

In mysql, I'm having trouble pulling a single row for each foreign_id based on the largest value . 在MySQL中,我无法拉动每个单行foreign_id基础上,最大的value Strangely, different versions of mysql works (listed below) 奇怪的是,不同版本的mysql可以正常工作(下面列出)

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 我尝试拉id 2,3,5而不是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)

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 在这种情况下,您需要JOIN而不是INNER JOIN

There is a difficult case where there are 2 or more foreign_id s with the same MAX value ... 困难的情况是存在两个或多个具有相同MAX value foreign_id ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM