MySQL获得组

时间:2016-01-21 16:41:20

标签: mysql

我有一个简单的一对多关系。一个表是专辑列表,另一个是照片列表。每张照片只能是一张相册,但相册中包含许多图片。

现在我想获得单个查询中所有相册的列表。我想要的信息是专辑本身的一些值(让我们说出专辑的name),该专辑中的总图像数量以及第一张图片的一些值。

我已经拥有了总图像数量和相册名称,但我在尝试获取第一个图像值时遇到了一些问题。

SELECT albums.id, albums.name, COUNT(photos.id) AS imageCount 
   FROM albums 
   LEFT JOIN photos ON albums.id = photos.albumid 
   GROUP BY name 
   ORDER BY id DESC

我尝试了other answers的几种方法,但我似乎做错了什么。由于我也在使用COUNT(),所以特别令人困惑。

我创建了一个sqlfiddle,其中包含此查询以及一个小样本数据库。那么我如何获得照片的第一个元素的一些值呢?

4 个答案:

答案 0 :(得分:3)

SELECT x.id
     , x.name
     , total
     , y.id
     , y.url
  FROM 
     ( SELECT a.*
            , COUNT(p.id) total
            , MIN(p.id) min_id
         FROM albums a
         LEFT
         JOIN photos p
           ON p.albumid = a.id
        GROUP
           BY a.id
     ) x
  LEFT
  JOIN photos y  
    ON y.id = x.min_id;

答案 1 :(得分:1)

你可以通过这个查询来做:

SELECT albums.id, 
       albums.name, 
       COUNT(photos.id) AS imageCount , 
       (select url 
        from photos 
        where id =(select min(id) 
                   from photos internal_photo 
                   where albums.id = internal_photo.albumid )) as photo_url
FROM albums 
LEFT JOIN photos ON albums.id = photos.albumid 
GROUP BY name 
ORDER BY id DESC

答案 2 :(得分:0)

我使用url格式获取第一个格式,如果你有不同的格式,你需要另一个连接来获得第一个。

SELECT A.*, P.url
FROM 
    (
      SELECT albums.id, albums.name, COUNT(photos.id) AS imageCount 
      FROM albums 
      LEFT JOIN photos ON albums.id = photos.albumid 
      GROUP BY name 
    ) A
LEFT JOIN (
        SELECT `albumid`, MIN(`url`) as `url`
        FROM photos
        GROUP BY `albumid`
    ) P
  ON A.id = P.`albumid`
ORDER BY id DESC

没有字符串麻烦的更通用的版本是:

<强> SQL Fiddle Demo

SELECT *
FROM 
    (
      SELECT albums.id, albums.name, COUNT(photos.id) AS imageCount 
      FROM albums 
      LEFT JOIN photos ON albums.id = photos.albumid 
      GROUP BY name 
      ORDER BY id DESC
    ) A
LEFT JOIN (
        SELECT photos.`albumid`, photos.`url`
        FROM photos
        LEFT JOIN (
                SELECT `albumid`, MIN(`id`) as `id`
                FROM photos p1
                GROUP BY `albumid`
              ) P1
          ON photos.`albumid` = p1.`albumid`
         AND photos.`id`  = P1.`id`
    ) P
  ON A.id = P.`albumid`

答案 3 :(得分:0)

如果您使用MySQL作为数据库,则可以运行此查询

SELECT albums.id, albums.name, photos.url, COUNT(photos.id) AS imageCount
FROM albums 
LEFT JOIN photos ON albums.id = photos.albumid 
GROUP BY name 
ORDER BY id DESC

因为MySQL中的分组总是返回第一行值。 CMIIW。 但您也可以尝试此查询(仅限嵌套子查询)。

SELECT albums.id, albums.name, COUNT(photos.id) AS imageCount, (
    SELECT photos.url 
    FROM photos 
    WHERE albums.id = photos.albumid 
    ORDER BY id ASC 
    LIMIT 1
)
FROM albums 
LEFT JOIN photos ON albums.id = photos.albumid 
GROUP BY name 
ORDER BY id DESC