2014-10-08 43 views
0

我们已经制定了一个两个表:使用相同的项目名称选择行和显示最低价格

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 

感谢,

里克

+0

你怎么知道哪个价格与产品有关?你确定'Prices.ID'将始终与'Product.ID'匹配吗? – Brewal 2014-10-08 13:21:53

+0

他们加入了ID。目前它只是显示最高价格。 – 2014-10-08 13:24:23

+1

这意味着一个产品只能有一个价格......那么你为什么不在产品表中添加一个字段'price'? – Brewal 2014-10-08 13:25:11

回答

0

第一的所有表的实现必须改善,如果您有ID为Products表中数据主键将如下(你需要一个主键)。

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; 
0
/* 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); 

(若有几个产品具有相同的项目价值和价格此查询会同时显示产品)

+0

谢谢,完全理解。用名称和最低价格创建一个表,然后获得与之匹配的产品的ID。虽然我在子选择中使用MIN()时遇到了问题。它总是挂起,当查询被执行,但如果我只是在子查询中提到一个名称的项目(WHERE item =“哈利波特”),并删除min()它工作正常。 – 2014-10-08 16:11:32

相关问题