【问题标题】:MySQL, to reverse SELECT GROUP BYMySQL,反向 SELECT GROUP BY
【发布时间】:2016-11-22 03:19:37
【问题描述】:

我已经检查了具有类似问题的帖子(123 ...),但在 MySQL57(mysql-installer-community-5.7.13.0.msi)上没有适合我的解决方案。我想要做的是反向“分组”(从表格底部向上)。真的不明白为什么下面的查询不起作用。

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

【问题讨论】:

    标签: mysql sql select group-by


    【解决方案1】:

    你根本不想要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
                );
    

    【讨论】:

    • 像魅力一样工作!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2016-08-14
    • 2019-04-30
    • 1970-01-01
    相关资源
    最近更新 更多