sql如何从内部连接中获取最大值行

rbpvctlc  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(304)

我的用例是这样的。
我有餐馆。
一家餐厅有许多餐厅的项目。
每个餐厅项目都有一个评分值。
我想把餐馆和那家餐馆最好的东西一起买。
我会是这样的。

SELECT * FROM RESTAURANTS 
WHERE RESTAURANT_IDS = 1,2,3,4,5 
LEFT JOIN RESTAURANT_ITEMS 
WHERE ratings = MAX(ratings)

在餐厅的table上。

id|name
-------------
1 |McDonalds
2 |Pizzahut
3 |Buger king
4 |KFC

餐厅内物品表

id|name      |rating| FK_RES_ID
----------------------------
1 |Pizza     |5     |2
2 |Lava cake |4     |2
3 |Veg burger|3     |4
4 |Chicken b |5.6   |4
5 |Ice cream |4.3   |1
6 |Burger    |5     |1

期望的输出是

id|name      |top item
----------------------
1 |McDonalds |Burger
2 |Pizzahut  |Pizza
3 |Buger king|Null
4 |KFC       |Chicken b
biswetbf

biswetbf1#

我想这就是你要找的。尝试并确认。:)

SELECT 
      res.ResName
      ,item.Name as ResItem
      ,(Select max(SubItem.rating) from RESTAURANT_ITEMS SubItem where res.RestaurantID= SubItem.RestaurantID) as Rating
FROM 
      RESTAURANTS res
LEFT JOIN 
      RESTAURANT_ITEMS item on res.RestaurantID = item.RestaurantID
WHERE 
      res.Restaurant_ID in (1,2,3,4,5)

问题更新后,编辑了以下部分

SELECT 
      res.Name as [Restaurant Name]
      ,item.Name as [Top Item]
FROM 
      RESTAURANTS res
LEFT JOIN 
      RESTAURANT_ITEMS item on res.RestaurantID = item.RestaurantID 
                            and rating = (select max(subItems.rating) from RESTAURANT_ITEMS subItems where subItems.RestaurantID = res.RestaurantID)
WHERE 
      res.Restaurant_ID in (1,2,3,4,5)

希望这对你有帮助:)

e4yzc0pl

e4yzc0pl2#

您可以在派生表中获得餐厅的最高评级值。
将它连接回主表以获得所需的输出
请尝试以下操作:

SELECT r.id, 
       r.name, 
       ri.name AS top_item 
FROM RESTAURANTS AS r 
LEFT JOIN (SELECT FK_RES_ID, MAX(rating) AS max_rating 
           FROM RESTAURANT_ITEMS 
           GROUP BY FK_RES_ID) AS dt 
  ON dt.FK_RES_ID = r.id 
LEFT JOIN RESTAURANT_ITEMS AS ri ON ri.FK_RES_ID = dt.FK_RES_ID AND 
                                    ri.rating = dt.max_rating 

WHERE r.id IN (1,2,3,4)

相关问题