2015-10-18 143 views
0

表:服務
顯示最新的ID和公司ID

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 

如何修改查詢以獲得預期的輸出?

+2

您是否想要基於該順序的最新3行?如果是這樣的話,你只需要在子句 –

回答

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

之後添加'LIMIT 3'即可,如果你不需要任何額外的列,那麼這個源代碼更可取。 –

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