MySQL,按组反向选择
我已经检查了带有类似问题(,…)的帖子,但在MySQL57(mysql-installer-community-5.7.13.0.msi)上没有解决方案对我有效。我想做的是以相反的方向进行分组(从表格底部向上)。真的不明白为什么下面的查询不起作用MySQL,按组反向选择,mysql,sql,select,group-by,Mysql,Sql,Select,Group By,我已经检查了带有类似问题(,…)的帖子,但在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 N
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
您根本不想按
分组。您只需要智能筛选:
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
);
您根本不想按分组。您只需要智能筛选:
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
);
像个魔术师一样工作!!像个魔术师一样工作!!