2

我有两张桌子,albums而且pictures...

picturesalbums与via有关系fk_albumID

现在我想尝试的是从中选择所有albums,同时计算有多少与albums...有关的图片

我试过: SELECT *, (SELECT COUNT(*) FROM pictures WHERE pictures.fk_albumID = albums.albumID) AS albumCount FROM pictures, albums

但是如果根本没有图片,这首先不会返回任何结果......然后它会根据计数重复结果。因此,如果相册有 3 张图片,那么当我将相册绑定到中继器时,我将在列表中获得 3 次相册。

我试过: SELECT COUNT(albums.albumID) AS albumCount, albums.albumName, albums.albumID FROM albums INNER JOIN pictures ON pictures.fk_albumID = albums.albumID GROUP BY albums.albumID, albums.albuName

但这仅显示有图片的相册...

4

5 回答 5

2

不过你很亲近。您只需要从 INNER JOIN 到 OUTER JOIN

SELECT COUNT(billeder.album_id) AS AlbumSize, 
       albums.album_name, 
       albums.album_id 
  FROM albums 
 LEFT OUTER JOIN billeder 
              ON billeder.album_home = albums.album_id 
 GROUP BY albums.album_id, albums.album_name
于 2012-10-10T10:36:01.757 回答
1

您可以使用子查询:

SELECT p.PicCount AS AlbumSize, 
  albums.album_name, 
  albums.album_id 
FROM albums a
INNER JOIN billeder b
  ON b.album_home = a.album_id 
LEFT JOIN 
(
  SELECT count(*) PicCount, fk_albumid
  FROM pictures
  GROUY BY fk_albumid
) p
  on a.album_id = p.fk_albumid
于 2012-10-10T10:21:50.000 回答
1
SELECT t1.album_title, isnull(sum(flag),0) AS PicCount
FROM albums AS t1
LEFT JOIN
(
SELECT *, 1 AS Flag
FROM pictures) AS t2
ON t1.fk_albumID = t2.fk_albumID
GROUP BY t1.album_title

链接到SQL 小提琴

于 2012-10-10T10:26:32.630 回答
0
SELECT (SELECT COUNT(1)
        FROM billeder
        WHERE billeder.album_home = albums.album_id) albumCount,
       albums.album_name,
       albums.album_id
FROM albums
于 2012-10-10T10:19:34.550 回答
0
select 
    AL.album_name, 
    AL.albumID, 
    (select count(*) from 
            ALBUMS AL1, 
            PICTURES PIC1 
     where  AL1.albumID = PIC1.albumID) as CNT_ALBUMID
from 
    ALBUMS AL

试试

于 2012-10-10T10:32:20.040 回答