我希望AlbumCategories
显示每个类别的Albums
计数,如下所示。
期望的结果:
Sports(2)
Education(3)
Community(0)
Something(0)
查询:
SELECT
AC.ACID, MAX(AC.Name) as Name,
COUNT(*) as Frequency
FROM
Album A
INNER JOIN
AlbumCategories AC ON A.ACID = AC.ACID
GROUP BY
AC.ACID
此查询仅返回AlbumCategories
,其中包含以上查询
Sports(2)
Education(3)
表相册类别:
ACID Name
1 Sports
2 Education
3 Community
4 Something
表相册:
AID ACID Name
1 1 Footbal season 2015
2 1 Footbal season 2016
3 2 Album one
4 2 Album Two
5 2 Album Three
表相册图片:
PID AID Image
答案 0 :(得分:3)
您需要使用RIGHT JOIN
。 INNER JOIN
仅提取连接表之间的匹配记录。从Album
表计算列不要使用*
架构设置
CREATE TABLE AlbumCategories
([ACID] int, [Name] varchar(9))
;
INSERT INTO AlbumCategories
([ACID], [Name])
VALUES
(1, 'Sports'),
(2, 'Education'),
(3, 'Community'),
(4, 'Something');
CREATE TABLE albums
([AID] int, [ACID] int, [Name] varchar(19))
;
INSERT INTO albums
([AID], [ACID], [Name])
VALUES
(1, 1, 'Footbal season 2015'),
(2, 1, 'Footbal season 2016'),
(3, 2, 'Album one'),
(4, 2, 'Album Two'),
(5, 2, 'Album Three');
查询
SELECT AC.ACID,
AC.NAME AS NAME,
Count(A.ACID) AS Frequency
FROM albums A
RIGHT JOIN AlbumCategories AC
ON A.ACID = AC.ACID
GROUP BY AC.ACID,
AC.NAME
结果:
╔══════╦═══════════╦═══════════╗
║ ACID ║ NAME ║ Frequency ║
╠══════╬═══════════╬═══════════╣
║ 1 ║ Sports ║ 2 ║
║ 2 ║ Education ║ 3 ║
║ 3 ║ Community ║ 0 ║
║ 4 ║ Something ║ 0 ║
╚══════╩═══════════╩═══════════╝