[英]In SQL, select all from table a where column a value equals the value of the most recent entry in table b?
我有一个表,其中包含一个项目的多个版本。 我可以进行的最简单的比较是拥有歌曲数据库,并且由于其中有多张专辑,因此可能会重复播放一首歌曲。 我想提取最新发布日期的歌曲。
歌曲表:
ID Title AlbumID GenreID ProducerID.......Many other columns
1 A Song 1 3 12
2 A Song 2 3 5
3 Sing 3 5 10
专辑表:
ID Title ReleaseDate
1 Album 2001-01-01
2 Greatest Hits 2010-01-01
3 Another Album 2005-01-01
我可以像这样根据标题拉回所有歌曲:
Select * from Songs where title like '%song%'
我想做这样的事情:
Select * from Songs where title like '%song%' and AlbumID In
(Select AlbumID from Albums where ***ReleaseDate is most recent***)
所以结果将是一首歌:
ID Title AlbumID GenreID ProducerID........Many other columns
2 A Song 2 3 5
任何帮助表示赞赏。 :)
原版的
Select * from Songs where title like '%song%' and AlbumID In
(从ReleaseDate最近的相册中选择AlbumID)尝试
Select * from Songs where title like '%song%' and AlbumID In
(Select AlbumID from Albums order by ReleaseDate DESC Limit 1)
这是一种独立于数据库的方法。
本质上,它生成按日期显示最新歌曲的数据子集。 然后,它根据歌曲的磁贴和最新日期的专辑中的日期,将此子集重新加入整个集合。
它确实有两个假设。
。
SELECT *
FROM Songs S
INNER JOIN ALBUM A
on S.ID = A.ID
INNER JOIN (
SELECT max(A.RealeaseDate) as Newest, S.Title
FROM SONGS S
INNER JOIN album A
on A.ID = S.AlbumID
GROUP BY S.Title) C
on C.Title = S.Title
and C.Newest= A.ReleaseDate
如果需要,此方法可让您从任何一个表中获取数据。 使用存在会更快,但是,它限制了可以返回的数据元素(列)。
我想我只需要在网上要求我找出答案。
select * from songs where title like '%song%' and
AlbumID In(Select distinct AlbumID from Albums where
albums.ReleaseDate= (Select Max(ReleaseDate) from albums))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.