我正在使用通过DBeaver获得的示例数据库。它包含一个名为Artists的表和一个名为Albums的表。有些艺术家没有专辑,有些只有一张,有些则很多。
我要实现的目标是向左连接以显示所有歌手,但仅显示只有一张专辑的歌手的专辑名称。
以下使用DBeaver可以工作,但是如果直接从MS Access中执行(我需要能够这样做)则不起作用:
SELECT
ar.AName,
al.title
FROM
Artist ar
LEFT JOIN (
SELECT
al.*
FROM
album al
INNER JOIN (
SELECT
artistid,
COUNT( artistid ) artistCount
FROM
album
GROUP BY
artistid ) alc ON
alc.artistid = al.artistid
AND alc.artistcount = 1 ) al ON
al.artistid = ar.artistid
ORDER BY
ar.aname
表包含以下列:
Artist
ArtistID (Key)
Name
Album
AlbumID (Key)
Title
ArtistID
非常感谢。我在任何地方都找不到答案。我了解MS Access中使用的SQL版本与其他各种变体中发现的版本不同。
欢呼
帕特里克
答案 0 :(得分:0)
我会选择NOT EXISTS
:
SELECT a.ArtistID, a.Name, al.Title
FROM Artist a LEFT JOIN
Album al
ON al.ArtistID = a.ArtistID AND
NOT EXISTS (SELECT 1
FROM Album al1
WHERE al1.ArtistID = al.ArtistID AND a1l.AlbumID <> al.AlbumID
);
答案 1 :(得分:0)
您不希望使用left join
。如果某位艺术家恰好拥有一张 张专辑,那么常规的join
就可以使用。关键是聚合:
select ar.aname, max(al.title) as title
from artist as ar inner join
album as al
on ar.artistid = al.artistid
group by ar.artistid, ar.aname -- I supposed two artists could have the same name
having count(*) = 1;
关键思想是,如果只有一张专辑,则max(al.title)
会返回该专辑的名称。
编辑:(基于评论)
select ar.aname,
switch(al.artistid is null, "No album"
count(*) = 1, max(al.title),
1=1, "> 1"
) as album_title
from artist as ar left join
album as al
on ar.artistid = al.artistid
group by ar.artistid, ar.aname;
答案 2 :(得分:0)
感谢您的帮助。我设法产生了我期望在MS Access中使用SQL的结果(将需要进行测试以确保其100%)。
我使用了以下内容:
SELECT
ar.AName,
al.title
FROM
Artist ar
LEFT JOIN (
SELECT
al.*
FROM
album al,
(
SELECT
al1.artistid,
COUNT( al1.artistid ) AS al1Count
FROM
album al1
GROUP BY
al1.artistid ) al1
WHERE
al.artistID = al1.artistid
AND al1.al1count = 1 ) al ON
al.artistid = ar.artistid
ORDER BY
ar.aname
再次感谢!