简体   繁体   中英

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

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.

  • The song tiles are identical.
  • if the same song is released on multiple albums on the same date, they both would be returned.

.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM