选择具有相同项目名称的行并显示最低价格值

时间:2014-10-11 10:42:31

标签: mysql

我们有两个表格:

Products
ID | Item | Supplier
1 | Harry Potter | Warner
2 | Harry Potter | Warner
3 | Game of Thrones | HBO
4 | The Simpsons | Warner
5 | The Simpsons | Warner

Prices
ID | Price
1 | 10.99
2 | 20.00
3 | 20.00
4 | 10.00
5 | 12.00

我正在尝试获得价格最低的商品的ID,其中有两个商品名称和供应商相同。

我可以获得重复的行:

SELECT
Products.ID,Products.Item,Products.Supplier,Prices.price
FROM
Products
LEFT JOIN Prices ON Prices.ID = Products.ID
WHERE Products.ID IN (
SELECT ID FROM Products WHERE Supplier="Warner" GROUP BY Item HAVING count(*) > 1
)

如何修改此项以仅显示价格最低的重复项目名称的Products.ID?

我尝试了ORDER BY,但这对我来说是一个错误。

结果应为:

ID | Item | Supplier | Price
1 | Harry Potter | Warner | 10.99
4 | The Simpsons | Warner | 10.00

谢谢,

瑞克

1 个答案:

答案 0 :(得分:1)

在子查询中使用ORDER BY,然后在主查询中使用GROUP BY

SELECT n.ID, n.Item, n.Supplier, n.Price
FROM 
  (SELECT p.ID, p.Item, p.Supplier, pr.Price
   Products p INNER JOIN Prices pr 
   ON p.ID = pr.ID
   ORDER BY price ASC) AS n
GROUP BY Item, Supplier

示例输出

ID   | Item            | Supplier | Price
1    | Harry Potter    | Warner   | 10.99
4    | The Simpsons    | Warner   | 10.00
3    | Game of Thrones | HBO      | 20.00

获得具有相同名称和供应商的两个项目的结果

SELECT n.ID, n.Item, n.Supplier, n.Price
FROM 
  (SELECT p.ID, p.Item, p.Supplier, pr.Price
   Products p INNER JOIN Prices pr 
   ON p.ID = pr.ID
   ORDER BY price ASC) AS n
GROUP BY Item, Supplier
HAVING COUNT(n.ID) > 1

示例输出

ID   | Item            | Supplier | Price
1    | Harry Potter    | Warner   | 10.99
4    | The Simpsons    | Warner   | 10.00