我有兩個表:產品和項目。我想根據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;
有Postgres裏一個'DISTINCT ON(...)' 「功能」。 –
這很可能不是他想要的。 Postgres提供'DISTINCT ON'。您的查詢也無法返回'items.id'。一個簡單的聚合函數('min()')就像你所建議的那樣不能返回所選行的附加列 - 而不是'DISTINCT ON'。 –