2014-10-08 42 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

相關問題