美文网首页
mysql group by 取最新一条记录

mysql group by 取最新一条记录

作者: 有趣有趣 | 来源:发表于2021-01-15 10:40 被阅读0次

SELECT
*
FROM
xc_reporting_task_detail rtd,
( SELECT max( id ) id FROM xc_reporting_task_detail GROUP BY task_id ) rtd2
WHERE
rtd.id = rtd2.id;

SELECT
*
FROM
xc_reporting_task_detail
WHERE
id IN ( SELECT MAX( id ) FROM xc_reporting_task_detail GROUP BY task_id )
3.如果排序字段不是id 是update_date
SELECT
*
FROM
( SELECT rtd.task_id, MAX( rtd.update_date ) AS update_date FROM xc_reporting_task_detail rtd GROUP BY rtd.task_id ) rtd
INNER JOIN xc_reporting_task_detail f ON f.task_id = rtd.task_id
AND f.update_date = rtd.update_date

sql数据
DROP TABLE IF EXISTS xc_reporting_task_detail;
CREATE TABLE xc_reporting_task_detail (
id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
task_id int(11) NOT NULL DEFAULT 0 COMMENT '办件id',
task_code varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '办件编码',
item_code varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '事项编码',
remarks varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '审批意见',
status char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '0' COMMENT '状态,0-待填报,1-待审核, 2-通过,3-驳回, 4-暂存',
update_date datetime(0) NOT NULL,
update_by varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
create_date datetime(0) NOT NULL,
create_name varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '创建人姓名',
create_by varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
del_flag char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '0' COMMENT '删除标志 0正常 1删除',
PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '填报任务详情表' ROW_FORMAT = Dynamic;


-- Records of xc_reporting_task_detail


INSERT INTO xc_reporting_task_detail VALUES (7, 2807, '330000000000210113000006', '330000000000000001', '通过', '2', '2021-01-13 20:27:30', '1', '2021-01-13 20:27:30', '超级管理员', '1', '0');
INSERT INTO xc_reporting_task_detail VALUES (8, 2808, 'xxx', '000000000000000001', '666666不让你通过', '3', '2021-01-14 15:43:49', '1', '2021-01-14 15:43:49', '超级管理员', '1', '0');
INSERT INTO xc_reporting_task_detail VALUES (9, 2808, 'xxx', '000000000000000001', '666666不让你通过2', '3', '2021-01-14 15:43:49', '1', '2021-01-14 15:43:49', '超级管理员', '1', '0');
INSERT INTO xc_reporting_task_detail VALUES (10, 2807, '330000000000210113000006', '330000000000000001', '驳回', '3', '2021-01-13 20:27:30', '1', '2021-01-13 20:27:30', '超级管理员', '1', '0');

相关文章

网友评论

      本文标题:mysql group by 取最新一条记录

      本文链接:https://www.haomeiwen.com/subject/efviaktx.html