max 需要两次 row_number 拳头,然后 Mim 也需要两次,因此每个配置文件只能获得一行
CREATE TABLE tableA (
`profile_id` INTEGER,
`id` INTEGER,
`created_at` datetime,
tableA int
);
INSERT INTO tableA
(`profile_id`, `id`, `created_at`)
VALUES
('1325586', '340807', '2021-08-05 21:30:55'),
('1325586', '340803', '2021-08-05 21:28:11'),
('1325586', '340805', '2021-08-05 21:28:11'),
('1325487', '340707', '2021-06-26 13:42:19'),
('1325487', '340453', '2021-03-25 10:49:40'),
('1325487', '340451', '2021-03-25 10:49:39');
CREATE TABLE tableB (p_id int,`type` VARCHAR(1))
INSERT INTO tableB VALUES(340807,'A'),(340803,'A'),(340805,'A'),(340707,'B'),(340453,'A'),(340451,'A')
WITH CTE AS(SELECT a.profile_id,a.id, a.created_at, b.type
FROM tableA a
JOIN tableB b ON a.id = b.p_id
)
SELECT
`profile_id`, `id`, `created_at`, `type`
FROM
(SELECT
t1.* , ROW_NUMBER() OVER( PARTITION BY `profile_id` ORDER BY created_at ASC) rn
FROM CTE t1
INNER JOIN (SELECT `profile_id`, `type`
FROM (
SELECT * , ROW_NUMBER() OVER( PARTITION BY `profile_id` ORDER BY created_at DESC) rn FROM CTE) ta
WHERE rn = 1) t2 ON t1.`profile_id` = t2.`profile_id` AND t1.`type` = t2.`type`) tb
WHERE rn = 1
profile_id |编号 | created_at |类型
---------: | -----: | :----------------- | :---
1325487 | 340707 | 2021-06-26 13:42:19 |乙
1325586 | 340803 | 2021-08-05 21:28:11 |一种
db小提琴here
对于 Mysql 5.7,这变得更丑了
CREATE TABLE tableA (
`profile_id` INTEGER,
`id` INTEGER,
`created_at` datetime,
tableA int
);
INSERT INTO tableA
(`profile_id`, `id`, `created_at`)
VALUES
('1325586', '340807', '2021-08-05 21:30:55'),
('1325586', '340803', '2021-08-05 21:28:11'),
('1325586', '340805', '2021-08-05 21:28:11'),
('1325487', '340707', '2021-06-26 13:42:19'),
('1325487', '340453', '2021-03-25 10:49:40'),
('1325487', '340451', '2021-03-25 10:49:39');
CREATE TABLE tableB (p_id int,`type` VARCHAR(1))
INSERT INTO tableB VALUES(340807,'A'),(340803,'A'),(340805,'A'),(340707,'B'),(340453,'A'),(340451,'A')
SELECT
`profile_id`, `id`, `created_at`, `type`
FROM
(SELECT IF(a.profile_id = @profile, @rn := @rn +1, @rn:= 1) rn,a.id, a.created_at, b.type,
@profile := a.profile_id as profile_id
FROM tableA a
JOIN tableB b ON a.id = b.p_id
JOIN
(SELECT profile_id,type
FROM
(SELECT IF(a.profile_id = @profile, @rn := @rn +1, @rn:= 1) rn,a.id, a.created_at, b.type,
@profile := a.profile_id as profile_id
FROM tableA a
JOIN tableB b ON a.id = b.p_id , (SELECT @profile := 0, @rn := 0 ) t1
ORDEr BY a.profile_id,a.created_at DESC) ta
WHERE rn = 1) tb ON a.profile_id = tb.profile_id AND b.type = tb.type,(SELECT @profile := 0, @rn := 0 ) t1
ORDER BY a.profile_id,a.created_at ASC) tc
WHERE rn = 1
profile_id |编号 | created_at |类型
---------: | -----: | :----------------- | :---
1325586 | 340807 | 2021-08-05 21:30:55 |一种
1325487 | 340707 | 2021-06-26 13:42:19 |乙
db小提琴here