sql语句,其中有top5和内连接

时间:2012-07-25 15:51:51

标签: mysql join

如何在top5和inner join中编写sql语句?

目前,这就是我所拥有的:

$query = "SELECT OrderItem.ProductCode , Product.ProductName, 
                 count(OrderItem.OrderID) as total_orders 
          FROM `OrderItem` 
          GROUP BY ProductCode 
          ORDER BY total_orders DESC LIMIT 5 
          INNER JOIN Product ON Product.ProductCode = OrderItem.ProductCode";

但它不起作用。

表: 产品表有列:

  ProductCode, ProductName, Cat, Qty, CostPr, RetailPr, VendorID

OrderItem表包含列:

  OrderID, ProductCode, UnitPr, Qty,TotalPr

我的目标是在提交的订单中显示前5个产品的产品代码和产品名称。请帮忙。谢谢。

2 个答案:

答案 0 :(得分:1)

A JOIN is part of the FROM clause, and should come before your GROUP BY

SELECT 
    OrderItem.ProductCode, 
    Product.ProductName, 
    count(OrderItem.OrderID) as total_orders 
FROM 
    OrderItem 
    INNER JOIN Product 
        ON Product.ProductCode = OrderItem.ProductCode
GROUP BY OrderItem.ProductCode, Product.ProductName 
ORDER BY total_orders DESC LIMIT 5 

答案 1 :(得分:0)

select ol.ProductCode, ol.total_orders, p.ProductName
from (
    select ProductCode, count(OrderID) as total_orders
    from OrderItem
    group by ProductCode
    order by total_orders desc LIMIT 5
) ol
inner join Product p on p.ProductCode = ol.ProductCode