2015-07-22 72 views
0

我想在sql问题上做一些练习问题,因为我意识到我在为它们奋斗。SQL查找最大类别

我一直在玩我的样本数据库,我试图列出餐厅名称,检查日期和总分数,但只显示每家餐厅检查的最近日期。

餐厅有一个摆脱检查和名称的外键。检查有一个摆脱,idate(检查日期)和检查totalscore。

我如何得到最近的检查分数和检查日期的餐馆列表?

SELECT i.idate, r.name, i.totalscore 
FROM restaurant r 
JOIN inspection i 
ON r.rid = i.rid where 
i.idate = (SELECT i1.idate 
        FROM restaurant r1 
        JOIN inspection i1 
        ON r1.rid = i1.rid 
      order by idate desc limit 1 
       ); 

谢谢!

+0

集团当我尝试这样做,编译器说,我不能组,因为该列不函数依赖? – ArtisticPhoenix

回答

0
按日期
+0

由餐厅为了要容易得多那么

SELECT i.idate, r.name, i.totalscore FROM restaurant r JOIN inspection i ON r.rid = i.rid where 1 GROUP BY r.name ORDER BY i.idate desc 
Akshay

+0

https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html – ArtisticPhoenix

+0

你可以尝试MAX(i.idate)而不是顺序,很难做到头部没有一个数据库设置来测试它。 – ArtisticPhoenix