MySQL JOIN,GROUP BY,ORDER BY

时间:2012-12-29 07:48:45

标签: mysql sql-order-by

我有一张产品表:

CREATE TABLE products (`id` INT);

这些产品的图像表:

CREATE TABLE images (`id` INT, `product_id` INT, `default` TINYINT(1));

我需要选择所有产品,并加入图片表,以便首选(default = 1)的图片,如果产品没有图片(default = 1) ,(default = 0)的图像将显示在其位置。


这是一张显示我正在寻找的图片:

enter image description here


现在我有这个问题:

SELECT p.id, i.id
FROM products AS p
LEFT JOIN (
    SELECT product_id, url
    FROM images
    ORDER BY default
) AS i
ON p.id = i.product_id
GROUP BY p.id
ORDER BY p.name

没有优先考虑“默认”图片。子查询似乎没有做任何事情。

4 个答案:

答案 0 :(得分:2)

SQLFiddle demo

select products.id,
       coalesce(t1.mid,t2.mid) as image_id      

from products
left join (select min(id) mid,product_id 
                  from images where `default`=1
                  group by product_id ) t1
        on products.id=t1.product_id
left join (select min(id) mid,product_id 
                  from images where `default`=0
                  group by product_id ) t2
        on products.id=t2.product_id

答案 1 :(得分:1)

看起来我在子查询的ORDER BY中错过了一个'DESC'

:\

答案 2 :(得分:0)

如果您只想显示产品的一张图片,请尝试此查询 -

SELECT p.*, i.* FROM products p
  JOIN (SELECT * FROM images ORDER BY `default` DESC) i
    ON p.id = i.product_id
GROUP BY p.id

答案 3 :(得分:0)

试试这个:

SELECT 
  p.id productid, 
  IFNULL(i1.id, i2.id)
FROM products    AS p
LEFT JOIN images AS i1  ON p.id = i1.product_id
                       AND i1.`Default` = 1  
LEFT JOIN images AS i2  ON p.id = i2.product_id
                       AND i2.`Default` = 0
GROUP BY p.id;