我有两张桌子,albums
和pictures
...
pictures
通过albums
与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
但这只显示有照片的专辑......
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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 Fiddle
答案 3 :(得分:0)
SELECT (SELECT COUNT(1)
FROM billeder
WHERE billeder.album_home = albums.album_id) albumCount,
albums.album_name,
albums.album_id
FROM albums
答案 4 :(得分: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
试一试