MySql:在连接表中返回MAX值

时间:2014-04-26 16:54:18

标签: mysql sql join max

我在这里加了3张桌子。客户订购的客户,订单和物品。这些名称为:CustomersTbl,OrdersTbl,OrderedItemTbl。

我正按照总价安排所有订单,并显示订单名称的客户。

select * from productstbl;
select * from ordereditemtbl;
select * from orderstbl;

select 
    ordereditemtbl.ItemID,
    customerstbl.CustomerID,
    customerstbl.FirstName,
    orderstbl.OrderID,
    orderstbl.OrderDate,
    sum(ordereditemtbl.amount * productstbl.Price) as totalPrice
from
    ordereditemtbl
        inner join
    ProductsTbl ON ordereditemtbl.productID = productstbl.productID
        inner join
    orderstbl ON ordereditemtbl.orderID = ordereditemtbl.orderID
        inner join
    customerstbl ON customerstbl.customerID = orderstbl.customerID#'2'
group by ordereditemTbl.OrderID
order by totalPrice desc;

现在我想单独显示TotalPrice最高的订单。我怎样才能得到它的最大值?有没有办法可以使用MAX()函数?

2 个答案:

答案 0 :(得分:1)

我们来看看。看看这是否有效:

SELECT * FROM 
(
select 
    ordereditemtbl.ItemID,
    customerstbl.CustomerID,
    customerstbl.FirstName,
    orderstbl.OrderID,
    orderstbl.OrderDate,
    sum(ordereditemtbl.amount * productstbl.Price) as totalPrice,
    @rownum AS row_number
from
    ordereditemtbl
        inner join
    ProductsTbl ON ordereditemtbl.productID = productstbl.productID
        inner join
    orderstbl ON ordereditemtbl.orderID = ordereditemtbl.orderID
        inner join
    customerstbl ON customerstbl.customerID = orderstbl.customerID#'2'
        inner join
    (SELECT @rownum := 0) dummy
group by ordereditemTbl.OrderID
ORDER BY totalPrice desc;
)
WHERE row_number=0

这会分配一个行号并选择最上一行。

干杯, 拉姆

答案 1 :(得分:0)

正如abl所建议的那样,我在代码末尾添加了以下内容:

order by totalPrice desc LIMIT 1;

显示创建的表的第一行,因为它以降序值显示。 谢谢!