简体   繁体   English

无法找出SQL查询

[英]Can't figure out SQL query

In my database I have certain categories of food in a table called foodgroups. 在我的数据库中,表中有某些类别的食物,称为foodgroups。 Therefore I have fooditems in a different table which relate to these categories. 因此,我在不同的表中有与这些类别相关的美食。 Moreover I created a table with orders called orders, and one "orderfood" table which defines the orders, in terms of how many of what products belong to an order. 此外,我还创建了一个包含订单的表,以及一个“ orderfood”表,该表根据订单中有多少产品来定义订单。

My intention is to show the most sold fooditems in each category of food. 我的目的是展示每种食品中销量最高的食品。 So I want to get out one column with the categories and next to it a collumn with the fooditem which was most sold of the fooditems in this category. 因此,我想列出一列带有类别的栏目,然后在其旁边列出一列带有食品项的栏目,该栏目是该类别中最畅销的食品项。

Select  foodgroups.name, SUM(orderfood.fooditem_ID*orderfood.amount)

FROM    orders, orderfood, products, productgroups

Where   productgroups.productgroup_ID=products.productgroup_ID

AND     orders.order_ID=orderfood.order_ID

AND     products.product_ID=orderfood.product_ID

Group by productgroups.productgroup_ID` 

So far it doesn't show any errors, but I have no clue how to get a column with only the most bought food next to its category where it is the most bought one. 到目前为止,它没有显示任何错误,但是我不知道如何获得一个列,该列中仅次于购买最多的食物是购买最多的食物。 Maybe you can help me, thank you :) 也许你可以帮我,谢谢:)

BTW, I am using the MySQL workbench. 顺便说一句,我正在使用MySQL工作台。

http://sqlfiddle.com/#!2/4b79c/2 http://sqlfiddle.com/#!2/4b79c/2

I think you're looking for the MAX function. 我认为您正在寻找MAX函数。 Add it to your select statement 将其添加到您的选择语句

Select  foodgroups.name, SUM(orderfood.fooditem_ID*orderfood.amount), max(orderfood.amount)

FROM    orders, orderfood, products, productgroups

Where   productgroups.productgroup_ID=products.productgroup_ID

AND     orders.order_ID=orderfood.order_ID

AND     products.product_ID=orderfood.product_ID

Group by productgroups.productgroup_ID` 

That should return you the most ordered food 那应该给你最有序的食物

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM