2010-06-05 53 views
13

下面是一個簡化的表結構:結果限制爲一個行

TABLE products (
product_id INT (primary key, auto_increment), 
category_id INT, 
product_title VARCHAR, 
etc 
); 

TABLE product_photos (
product_photo_id (primary key, auto_increment), 
product_id INT, 
photo_href VARCHAR, 
photo_order INT 
); 

產品可以具有多張照片,所述第一產品的照片爲每個產品(基於photo_order)是默認的照片。

現在,我只需要產品詳細信息頁面上的所有照片,但在列出多個產品的頁面上(例如產品目錄頁面),我只想顯示默認照片。

所以我想要做的是查詢產品列表,包括每個產品的默認照片。

這顯然是行不通的,它會返回所有的照片複製每張相片的產品信息:

SELECT p.*, ph.* 
FROM products AS p 
LEFT JOIN product_photos AS ph 
ON p.product_id=ph.product_id 
ORDER BY p.product_title ASC 

我需要弄清楚如何做這樣的事情,但我不知道語法(或者如果可能的話)

SELECT p.*, ph.* 
FROM products AS p 
LEFT JOIN product_photos AS ph 
    ON p.product_id=ph.product_id **ORDER BY ph.photo_order ASC LIMIT 1** 
ORDER BY p.product_title ASC 

編輯:我想通了,有幫助的解決方案,從下面的答案,謝謝大家!

SELECT p.*, ph.* 
FROM products AS p 
LEFT JOIN product_photos AS ph 
    ON p.product_id=ph.product_id 
    AND ph.photo_order = 
    (
     SELECT MIN(z.photo_order) 
     FROM product_photos AS z 
     WHERE z.product_id=p.product_id 
    ) 
GROUP BY p.product_id 
ORDER BY p.product_title ASC 
+0

請提供PRODUCT_PHOTOS的一個例子 - 我想看看PHOTO_ORDER如何控制默認的,因爲你沒有提供的數據類型 – 2010-06-05 01:26:26

+0

photo_order僅僅是一個整數,它應該* *每產品唯一的,但有必要保證 – Rob 2010-06-05 01:40:54

+0

如果你切換到正確的加入和秩序:.product_title ASC,.photo_order ASC我想你會得到每行產品一行,這將是第一張照片。你不會看到沒有照片的產品(這可能是一個問題)。但它應該是一個更簡單的查詢。 – TheJacobTaylor 2010-06-05 01:43:12

回答

6

用途:

SELECT p.*, 
     pp.* 
    FROM PRODUCTS p 
    JOIN PRODUCT_PHOTOS pp ON pp.product_id = p.product_id 
    JOIN (SELECT x.product_id, 
       MIN(x.photo_order) AS default_photo 
      FROM PRODUCT_PHOTOS x 
     GROUP BY x.product_id) y ON y.product_id = pp.product_id 
           AND y.default_photo = pp.photo_order 
+0

我不知道這是他要求的。他具體說明使用photo_order字段,而不是product_photo_id字段。 – 2010-06-05 01:28:55

+0

它確實需要什麼,我只是儘量避免子查詢,因此可以回答其他問題。 – Wrikken 2010-06-05 01:31:30

+0

@Wrikken:對派生表/內聯視圖的連接不是子查詢。對我而言,至少... – 2010-06-05 01:34:20

12
SELECT p.*, ph.* 
FROM products AS p 
INNER JOIN product_photos AS ph 
    ON p.product_id = ph.product_id 
LEFT JOIN product_photos AS ph2 
    ON p.product_id = ph2.product_id 
    AND ph2.photo_order < ph.photo_order 
WHERE ph2.photo_order IS NULL 
ORDER BY p.product_title ASC 

注意它是如何加入到product_photos表的兩倍。 WHERE ph2.photo_order IS NULL將會丟棄除最低照片順序以外的所有照片。它不會保護您免受重複的product_id/photo_orders組合,儘管如此,您可以在p.id上添加GROUP BY

+0

感謝您的回覆! – Rob 2010-06-05 01:41:19

+2

幹得好。沒有子查詢/派生表。只需要索引product_id和photo_order。 – 2010-06-05 02:00:58

1
SELECT ... 
    .... 
GROUP BY p.product_id 
+0

感謝您的回覆,雖然此解決方案不會兌現photo_order專欄。 – Rob 2010-06-05 01:44:39

+0

嘗試顛倒排序順序。 – 2010-06-05 01:51:31

4
SELECT p.*, ph.* 
    FROM products AS p 
    LEFT JOIN product_photos AS ph ON p.product_id=ph.product_id 
    ORDER BY p.product_title ASC, ph.photo_order ASC 
    GROUP BY p.product_id 
    LIMIT 0,10