[英]In SQL, select all from table a where column a value equals the value of the most recent entry in table b?
I have a table with multiple versions of an item. 我有一个表,其中包含一个项目的多个版本。 The easiest comparison I can give is having a database of songs and there could be a song repeated because it is on multiple albums.
我可以进行的最简单的比较是拥有歌曲数据库,并且由于其中有多张专辑,因此可能会重复播放一首歌曲。 I want to pull the song with the latest release date.
我想提取最新发布日期的歌曲。
Songs Table: 歌曲表:
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
Album Table: 专辑表:
ID Title ReleaseDate
1 Album 2001-01-01
2 Greatest Hits 2010-01-01
3 Another Album 2005-01-01
I can pull back all the songs based on title like this: 我可以像这样根据标题拉回所有歌曲:
Select * from Songs where title like '%song%'
I want to do something like this: 我想做这样的事情:
Select * from Songs where title like '%song%' and AlbumID In
(Select AlbumID from Albums where ***ReleaseDate is most recent***)
So the result will be one Song: 所以结果将是一首歌:
ID Title AlbumID GenreID ProducerID........Many other columns
2 A Song 2 3 5
Any help is appreciated. 任何帮助表示赞赏。 :)
:)
original 原版的
Select * from Songs where title like '%song%' and AlbumID In
(Select AlbumID from Albums where ReleaseDate is most recent ) try this (从ReleaseDate最近的相册中选择AlbumID)尝试
Select * from Songs where title like '%song%' and AlbumID In
(Select AlbumID from Albums order by ReleaseDate DESC Limit 1)
Here's one method independent of database. 这是一种独立于数据库的方法。
Essentially it generates a subset of data showing the newest song by date. 本质上,它生成按日期显示最新歌曲的数据子集。 It then joins this subset back to your entire set based on the song tile and date on the album with the newest date.
然后,它根据歌曲的磁贴和最新日期的专辑中的日期,将此子集重新加入整个集合。
It does make a couple of assumptions. 它确实有两个假设。
. 。
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
This method allows you to get data from either table if needed. 如果需要,此方法可让您从任何一个表中获取数据。 using an exists would be faster, however, it limits the data elements (columns) which can be returned.
使用存在会更快,但是,它限制了可以返回的数据元素(列)。
I guess I just needed to ask online for me to figure out the answer. 我想我只需要在网上要求我找出答案。
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.