2013-07-08 92 views
1

我有兩個表:產品和項目。我想根據condition列選擇屬於某個產品的distinct項,按price ASC排序。選擇DISTINCT返回的記錄太多

+-------------------+ 
| id | name   | 
+-------------------+ 
| 1 | Mickey Mouse | 
+-------------------+ 

+-------------------------------------+ 
| id | product_id | condition | price | 
+-------------------------------------+ 
| 1 | 1   | New  | 90 | 
| 2 | 1   | New  | 80 | 
| 3 | 1   | Excellent | 60 | 
| 4 | 1   | Excellent | 50 | 
| 5 | 1   | Used  | 30 | 
| 6 | 1   | Used  | 20 | 
+-------------------------------------+ 

所需的輸出:

+----------------------------------------+ 
| id | name   | condition | price | 
+----------------------------------------+ 
| 2 | Mickey Mouse | New  | 80 | 
| 4 | Mickey Mouse | Excellent | 50 | 
| 6 | Mickey Mouse | Used  | 20 | 
+----------------------------------------+ 

這裏的查詢。它返回六個記錄,而不是所需的三個:

SELECT DISTINCT(items.condition), items.price, products.name 
FROM products 
INNER JOIN items ON products.id = items.product_id 
WHERE products.id = 1 
ORDER BY items."price" ASC, products.name; 

回答

3

正確PostgreSQL的查詢:

SELECT DISTINCT ON (items.condition) items.id, items.condition, items.price, products.name 
FROM products 
INNER JOIN items ON products.id = items.product_id 
WHERE products.id = 1 
ORDER BY items.condition, items.price, products.name; 

SELECT DISTINCT ON(表達式[,...])只保留每個 第一行給定表達式求值相等的行集合。

詳細here

0

使用SELECT GROUP BY,僅提取每個PRODUCT/CONDITION的MIN(價格)。

3

SQL中沒有distinct()函數。您的查詢被解析爲

SELECT DISTINCT (items.condition), ... 

這相當於

SELECT DISTINCT items.condition, ... 

DISTINCT適用於整行 - 如果兩個或更多的行都有相同的字段值,然後將「複製」行從結果集中刪除。

你可能想要的東西更像

SELECT items.condition, MIN(items.price), products.name 
FROM ... 
... 
GROUP BY products.id 
+1

有Postgres裏一個'DISTINCT ON(...)' 「功能」。 –

+1

這很可能不是他想要的。 Postgres提供'DISTINCT ON'。您的查詢也無法返回'items.id'。一個簡單的聚合函數('min()')就像你所建議的那樣不能返回所選行的附加列 - 而不是'DISTINCT ON'。 –

2

我要選擇屬於基礎上, 狀態欄,按價格排序ASC產品不同的項目。

你最想DISTINCT ON

SELECT * 
FROM (
    SELECT DISTINCT ON (i.condition) 
      i.id AS item_id, p.name, i.condition, i.price 
    FROM products p 
    JOIN items i ON i.products.id = p.id 
    WHERE p.id = 1 
    ORDER BY i.condition, i.price ASC 
    ) sub 
ORDER BY item_id; 

由於ORDER BY領先的列有匹配DISTINCT ON使用的列,你需要一個子查詢獲得的排序順序您顯示。

更妙的是:

SELECT i.item_id, p.name, i.condition, i.price 
FROM (
    SELECT DISTINCT ON (condition) 
      id AS item_id, product_id, condition, price 
    FROM items 
    WHERE product_id = 1 
    ORDER BY condition, price 
    ) i 
JOIN products p ON p.id = i.product_id 
ORDER BY item_id; 

應該是快了些。

另外:您不應該使用非描述性名稱id作爲標識符。改爲使用item_idproduct_id

更多詳細信息,鏈接和基準測試在此相關的答案:
Select first row in each GROUP BY group?