加入相册及其图像数量和封面?

时间:2014-10-25 03:50:49

标签: mysql sql join

我正在尝试使用MySQL从两个表中获得某些结果,下面是两个表的格式:

          Albums                                         Images
------------------------------                 ----------------------------
  id   |   name  |   cover                       id |   image     | album
------------------------------                 ----------------------------
  1    | album1  |    3                          1  | image1.jpg  |   2
  2    | album2  |    1                          2  | image2.jpg  |   3
  3    | album3  |    0                          3  | image3.jpg  |   1
  4    | album4  |    0                          4  | image4.jpg  |   1
------------------------------                   5  | image5.jpg  |   3
                                                 6  | image6.jpg  |   1
                                               ----------------------------

现在给出上面的表格,我希望结果如下:

---------------------------------------
  id  |  name  |  count |  cover
---------------------------------------
  1   | album1 |   3    |  image3.jpg
  2   | album2 |   1    |  image1.jpg
  3   | album3 |   2    |    null
  4   | album4 |   0    |    null 
---------------------------------------
  • count是指定相册中的图片数量
  • cover是ID与相册封面栏
  • 相匹配的图片

我尝试了一些查询,但没有一个能给我预期的结果。

SELECT a.id, 
       a.name, 
       count(p.id) AS imageCount, 
       (SELECT image 
          FROM albums, 
               photos 
         WHERE albums.cover = photos.id)
  FROM photos p
RIGHT OUTER JOIN albums a
              ON a.id=p.album
  GROUP BY a.id;

这导致每行列出相同的封面图片。

我也试过这个:

SELECT a.id, 
       a.name, 
       count(p.id) AS imageCount, 
       coverTable.image
  FROM photos p
RIGHT OUTER JOIN albums a
              ON a.id=p.album
RIGHT OUTER JOIN (SELECT albums.id, 
                         image 
                     FROM albums, 
                          photos 
                    WHERE albums.cover = photos.id) AS coverTable
              ON coverTable.id = a.id
        GROUP BY a.id;

这只会为一张有封面图片的相册产生一行。

2 个答案:

答案 0 :(得分:2)

SELECT a.id, a.name, count(p1.id) AS imageCount, p2.image as cover
FROM albums a
LEFT JOIN photos p1 ON p1.album = a.id
LEFT JOIN photos p2 ON p2.id = a.cover
GROUP BY a.id

DEMO

答案 1 :(得分:0)

select a.id
    ,a.name 
    ,(select COUNT(album) from @Img where album=a.id ) as cont
    ,i.imagename as cover from @albums a
left outer join @Img i on a.cover = i.id