【问题标题】:Select rows with the same Item name and show lowest Price选择具有相同项目名称的行并显示最低价格
【发布时间】:2014-10-08 23:12:59
【问题描述】:

我们有两个表格,布局如下:

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

谢谢,

瑞克

【问题讨论】:

  • 您如何知道与产品相关的价格?您确定 Prices.ID 将始终匹配 Product.ID 吗?
  • 他们在 ID 上加入。目前它只是显示最高价格。
  • 这意味着一个产品只能有一个价格......那你为什么不在Products表中添加一个字段price
  • 这仍然只是给出具有相同名称的行值,而不是显示价格最低的重复项目,还是我错过了一些简单的东西!?

标签: mysql


【解决方案1】:

首先,如果您在 Products 表中将 ID 作为主键,则必须改进表的实现,您的数据将如下所示(您需要一个主键)。

Products
ID | Item | Supplier
1 | Harry Potter | Warner
2 | Game of Thrones | HBO

Prices
ID | Price
1 | 10.99
1 | 20.00
2 | 20

现在为了选择最低价格的商品,请使用 min 函数

SELECT
Products.ID,Products.Item,Products.Supplier, MIN(Prices.price)
FROM
Products
LEFT JOIN Prices ON Prices.ID = Products.ID;

【讨论】:

    【解决方案2】:
    /* Oracle syntax  
    with Products as  
    (  
    select 1 id, 'Harry Potter' item,  'Warner' supplier from dual union all  
    select 2 id, 'Harry Potter' item,  'Warner' supplier from dual union all  
    select 3, 'Game of Thrones', 'HBO' from dual union all  
    select 4, 'the simpsons', 'Warner' from dual union all  
    select 5, 'the simpsons', 'Warner' from dual  
    ),  
    Prices as  
    (  
    select 1 id, 10.99 price from dual union all  
    select 2, 20.00 from dual union all   
    select 3, 20.00 from dual union all  
    select 4, 10.00 from dual union all  
    select 5, 12.00 from dual)  
    */  
    
    select distinct p.id from Products p join Prices c  
    on (p.id = c.id)   
    where (p.item, p.supplier, c.price) in  
    (select item, supplier, min(price) from Products p join Prices c on (p.id = c.id) group by item, supplier having count(item) > 1);
    

    (如果多个产品具有相同的项目价值和价格,则此查询将显示两种产品)

    【讨论】:

    • 谢谢,完全了解理论。创建一个包含名称和最低价格的表,然后获取与之匹配的产品的 ID。我在子选择中使用 MIN() 时遇到问题。执行查询时它总是挂起但是如果我只是在子查询中按名称提及一个项目 (WHERE item="harry potter") 并删除 min() 它工作正常。
    猜你喜欢
    • 1970-01-01
    • 2016-03-18
    • 2018-03-16
    • 2020-03-19
    • 2012-08-12
    • 2017-05-23
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多