表:服务
id companyid jobid
1 1 1
2 1 2
3 1 2
4 2 3
5 3 4
6 3 1
7 4 2
8 5 2
我输入以下查询:
SELECT *
FROM service
WHERE jobID = 2
ORDER BY companyID desc, ID desc
我得到以下输出:
id companyid jobid
8 5 2
7 4 2
3 1 2
2 1 2
但我希望我的预期输出如下:
id companyid jobid
8 5 2
7 4 2
3 1 2
如何修改查询以获得预期的输出?
答案 0 :(得分:3)
您应该只需应用max
函数和group by
子句:
select max(id) id, companyid, jobid
from service
where jobid = 2
group by companyid, jobid
order by id desc
根据您的样本数据,结果将是:
id companyid jobid
8 5 2
7 4 2
3 1 2
答案 1 :(得分:2)
这应该有效:
select * from service s1
join (select max(id) as id
from service
group by jobid, companyid) s2 on s1.id = s2.id
where s1.jobid = 2--can comment to select all latest jobs