MySQL,用于反转SELECT GROUP BY

时间:2016-11-22 03:19:37

标签: mysql sql select group-by

我已使用类似问题(123 ...查看了帖子,但在MySQL57上没有解决方案适用于我(mysql-installer-community-5.7 .13.0.msi)。我想做的是" group by"反方向(从桌子底部向上)。真的不明白为什么以下查询无法正常工作。

use db;

# create the table. k guarantees increase.
CREATE TABLE `db`.`test` (
  `k` INT NOT NULL,
  `a` INT NULL,
  `b` INT NULL,
  `c` INT NULL,
 PRIMARY KEY (`k`));

# populate data
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('1', '1', '10', '100');
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('2', '2', '20', '200');
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('3', '1', '10', '300');
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('4', '3', '30', '700');
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('5', '3', '30', '800');

# want to query the last entry of each unique a+b
Select * From 
    (Select * From test Order By k Desc) As t
    Group By t.a, t.b;

我得到的是

k a b  c
1 1 10 100
2 2 20 200
4 3 30 700

但我想要的是如下,顺序并不重要。

k a b  c
5 3 30 800
3 1 10 300
2 2 20 200

1 个答案:

答案 0 :(得分:2)

你根本不想要group by。你只想要智能过滤:

Select t.*
From test t
where t.k = (select max(t2.k)
             from test t2
             where t2.a = t.a and t2.b = t.b
            );