将连接表的结果限制为一行

时间:2010-06-05 01:19:29

标签: sql mysql

这是一个简化的表结构:

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

4 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:10)

使用:

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

答案 2 :(得分: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

答案 3 :(得分:1)

SELECT ...
  ....
GROUP BY p.product_id