SQL选择条目及其关联的图像

时间:2012-01-08 22:04:04

标签: mysql sql database

我没有那么多SQL,所以我在这一点上迷失了。

我有三张桌子:

images(id,image_path)

shop_entries(id,title,....)

shop_img(shop_id,img_id)

我想显示所有商店条目及其相关图片。目前我的SQL正在返回shop_entries多次(每次都有1个与之关联的图像)。我想仅返回shop_entries一次,但链接了多个图像。

我的SQL看起来像这样:

SELECT s.*, images.*  
FROM shop_entries s 
LEFT JOIN shop_img ON shop_img.shop_id = s.id 
LEFT JOIN images ON images.id = shop_img.img_id 

更新* 下面的答案有效,但现在我想在查询中添加另一个表,原理相同:除了图像,我还有一个表“sizes”和“shop_sizes”。

此查询导致双重图像和双倍大小,这里有什么问题:

Select SE.*

 , Group_Concat(I.path Order By I.path ASC Separator ', ') as images
 , Group_Concat(S.title Order By S.title ASC Separator ', ') as sizes
 From shop_entries As SE

            Left Join shop_img As SI
                On SI.shop_id = SE.id
            Left Join images As I
                On I.id = SI.img_id

            Left Join shop_sizes As SS
                On SS.shop_id = SE.id
            Left Join sizes As S
                On S.id = SS.size_id

        Group By SE.id, SE.title

2 个答案:

答案 0 :(得分:3)

Select SE.ie, SE.title
    , Group_Concat(I.image_path Order By I.image_path ASC Separator ', ')
From shop_entries As SE
    Left Join shop_img As SI
        On SI.shop_id = SE.id
    Left Join images As I
        On I.id = SI.img_id
Group By SE.ie, SE.title

答案 1 :(得分:1)

分别对图像和尺寸进行分组,然后将结果集连接到shop_entries以获得最终输出:

SELECT
  SE.*,
  COALESCE(GI.images, '') AS images,
  COALESCE(GS.sizes,  '') AS sizes
FROM shop_entries AS SE

  LEFT JOIN (
    SELECT
      SI.shop_id,
      GROUP_CONCAT(I.path ORDER BY I.path ASC SEPARATOR ', ') AS images
    FROM shop_img AS SI
      INNER JOIN images AS I ON SI.img_id = I.id
    GROUP BY SI.shop_id
  ) AS GI ON SE.id = GI.shop_id

  LEFT JOIN (
    SELECT
      SS.shop_id,
      GROUP_CONCAT(S.title ORDER BY S.title ASC SEPARATOR ', ') AS sizes
    FROM shop_sizes AS SS
      INNER JOIN sizes AS S ON SS.size_id = S.id
    GROUP BY SS.shop_id
  ) AS GS ON SE.id = GS.shop_id