我有 2 张 table :
表 1:
| jobid | jobname |
| 1 | job a |
| 2 | job b |
表 2:
| id | jobid | statusid | statusdate | desc |
| 1 | 1 | 100 | 2019.04.25 10:00:00 | first |
| 2 | 2 | 100 | 2019.04.25 11:00:00 | first |
| 3 | 2 | 100 | 2019.04.25 12:00:00 | second |
table2 中的作业可以有多个相同的“statusid”,但“statusdate”和“desc”不同
我需要获取最后一个“statusid”= 100 的职位列表,如下所示:
| 1 | job a | 1 | 1 | 100 | 2019.04.25 10:00:00 | first |
| 2 | job b | 3 | 2 | 100 | 2019.04.25 12:00:00 | second |
SELECT * FROM table1
INNER JOIN table2 ON table1.id = table2.jobid
GROUP BY table1.id
此查询返回错误结果,例如:
| 1 | job a | 1 | 1 | | 100 | 2019.04.25 10:00:00 | first |
| 2 | job b | 3 | 2 | 2 | 100 | 2019.04.25 11:00:00 | first |
最佳答案
您应该能够通过执行以下操作来实现这一目标:
表格
drop table if exists table1;
create table table1 (jobid int, jobname char(10));
insert into table1 values (1, 'job a'), (2, 'job b');
drop table if exists table2;
create table table2 (
id int,
jobid int,
statusid int,
statusdate timestamp,
`desc` char(10)
);
insert into table2 values
(1,1,100,'2019.04.25 10:00:00','first')
,(2,2,100,'2019.04.25 11:00:00','first')
,(3,2,100,'2019.04.25 12:00:00','second');
查询
select
t1.*,
t2.*
from table1 t1
inner join (
select jobid, max(statusdate) as maxstatusdate
from table2
group by jobid
) tn on t1.jobid = tn.jobid
inner join table2 t2 on tn.jobid = t2.jobid and tn.maxstatusdate = t2.statusdate;
结果
jobid jobname id jobid statusid statusdate desc
1 job a 1 1 100 25.04.2019 10:00:00 first
2 job b 3 2 100 25.04.2019 12:00:00 second
说明
- 对于每个职位 ID,查找最长状态日期
- 将其连接到 table1 以从 table1 获取信息。公共(public)字段是jobid
- 将他们的结果连接到包含您想要的所有剩余信息的表 2 中。常见字段有 jobid 和 statusdate。由于我们将最大状态日期别名为不同的名称,因此请确保我们在联接中使用正确的名称
关于mysql - 从连接表中获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852211/