sql获取所有具有类型工作和年份大于属于该专辑的情歌的歌曲

6jjcrrmo  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(258)

我有一个表称为专辑,每个有标题的歌曲,歌曲列表,每个歌曲属于特定的专辑和歌曲详情如下
专辑

AlbumCode   TitleSong
A1           TS1
A2           TS2

歌曲列表

SongCode    AlbumCode
TS1          A1
S2           A1
S3           A1
TS2          A2
S5           A2

歌曲详细信息

id  Song    type          year  
1   TS1     love          2016  
2   S2      partialLove   2016  
3   TS1     partialLove   2016  
4   S3      work          2017

问题是:我需要得到所有的歌曲有类型的工作,并有一年大于情歌属于该专辑。所以在这种情况下,预期的输出是 4 S3 work 2017 我正在努力加入3个表,但无法得到所需的输出这是我一直尝试到现在,如何比较这两个结果在单一的查询,并得到结果,这将给我的歌曲列表

select * from Albums a join AlbumSongList asl ON a.AlbumCode = asl.AlbumCode
JOIN songManagement sm ON sm.Song=asl.SongCode WHERE sm.type = 'work'

select * from Albums a join AlbumSongList asl ON a.AlbumCode = asl.AlbumCode
JOIN songManagement sm ON sm.Song=asl.SongCode WHERE sm.type = 'love'
ih99xse1

ih99xse11#

好像是个 EXISTS 将用于以下目的:

--Sample data
--We never actually use Albums
WITH Albums AS(
    SELECT *
    FROM (VALUES('A1','TS1'),
                ('A2','TS2'))V(AlbumCode,TitleSong)),
SongList AS(
    SELECT *
    FROM (VALUES('TS1','A1'),
                ('S2','A1'),
                ('S3','A1'),
                ('TS2','A2'),
                ('S5','A2'))V(SongCode, AlbumCode)),
SongDetails AS(
    SELECT *
    FROM (VALUES(1,'TS1','love',2016),
                (2,'S2','partialLove',2016),
                (3,'TS1','partialLove',2016),
                (4,'S3','work',2017))V(id, Song, type, year))
--Solution
SELECT SDw.id,
       SDw.Song,
       SDw.type,
       SDw.year
FROM SongList SLw
     JOIN SongDetails SDw ON SLw.SongCode = SDw.Song
WHERE SDw.type = 'work'
  AND EXISTS (SELECT 1
              FROM SongList SLl
                   JOIN SongDetails SDl ON SLl.SongCode = SDl.Song
              WHERE SLl.AlbumCode = SLw.AlbumCode
                AND SDl.year < SDw.year
                AND SDl.type = 'love');

相关问题