6

我有一张产品表:

CREATE TABLE products (`id` INT);

以及这些产品的图片表:

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

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


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

在此处输入图像描述


现在我有这个查询:

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

4 回答 4

2

SQLFiddle 演示

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
于 2012-12-29T08:07:55.497 回答
1

看起来我只是在子查询的 ORDER BY 中遗漏了一个“DESC”

:\

于 2012-12-29T07:55:50.973 回答
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
于 2012-12-29T07:56:10.410 回答
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;
于 2012-12-29T07:58:07.087 回答