Mysql left join获取分组后最新日期的记录

select name, max(value)
from out_pumptable
group by name
# 创建表
CREATE TABLE IF NOT EXISTS `runoob_tbl`(
   `runoob_id` INT UNSIGNED,
   `runoob_title` VARCHAR(100) NOT NULL,
   `runoob_author` VARCHAR(40) NOT NULL,
   `submission_date` DATE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

# 插入数据
INSERT INTO runoob_tbl
(runoob_id,runoob_title, runoob_author, submission_date)
VALUES
(1, "学习 PHP", "菜鸟教程", NOW());

INSERT INTO runoob_tbl
(runoob_id,runoob_title, runoob_author, submission_date)
VALUES
(2, "学习 PHP", "菜鸟教程", NOW());

INSERT INTO runoob_tbl
(runoob_id,runoob_title, runoob_author, submission_date)
VALUES
(3, "学习 PHP", "菜鸟教程", NOW());

INSERT INTO runoob_tbl  VALUES (1, "学习 PHP222", "菜鸟教程1212", '2022-01-23');

mysql> select * from runoob_tbl;
+-----------+--------------+---------------+-----------------+
| runoob_id | runoob_title | runoob_author | submission_date |
+-----------+--------------+---------------+-----------------+
|         1 | 学习 PHP     | 菜鸟教程      | 2021-01-26      |
|         2 | 学习 PHP     | 菜鸟教程      | 2021-01-26      |
|         1 | 学习 PHP     | 菜鸟教程      | 2021-01-26      |
|         3 | 学习 PHP     | 菜鸟教程      | 2021-01-26      |
|         1 | 学习 PHP     | 菜鸟教程      | 2022-01-23      |
+-----------+--------------+---------------+-----------------+
5 rows in set (0.00 sec)

mysql> select runoob_id, max(submission_date) as max_date from runoob_tbl group by runoob_id;
+-----------+------------+
| runoob_id | max_date   |
+-----------+------------+
|         1 | 2022-01-23 |
|         2 | 2021-01-26 |
|         3 | 2021-01-26 |
+-----------+------------+

mysql> select a.* from runoob_tbl a left join (select runoob_id, max(submission_date) as max_date 
from runoob_tbl group by runoob_id)b on a.runoob_id = b.runoob_id where a.submission_date = b.max_date; +-----------+---------------+------------------+-----------------+ | runoob_id | runoob_title | runoob_author | submission_date | +-----------+---------------+------------------+-----------------+ | 2 | 学习 PHP | 菜鸟教程 | 2021-01-26 | | 3 | 学习 PHP | 菜鸟教程 | 2021-01-26 | | 1 | 学习 PHP222 | 菜鸟教程1212 | 2022-01-23 | +-----------+---------------+------------------+-----------------+ drop table runoob_tbl;
参考:
https://stackoverflow.com/questions/4510185/select-max-value-of-each-group
https://www.runoob.com/mysql/mysql-create-tables.html
posted @ 2021-01-26 20:14  船长博客  阅读(1362)  评论(0编辑  收藏  举报
永远相信美好的事情即将发生!