1
votes

How do i write a sql statement where there is top5 and inner join?

Currently, this is what i have:

$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";

but it's not working.

tables: Product table has columns:

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

OrderItem table has columns:

  OrderID, ProductCode, UnitPr, Qty,TotalPr

My objective is to display the productcode and productname of the top 5 products in orders submitted. Please help. thanks.

2

2 Answers

1
votes

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 
0
votes
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