簡體   English   中英

在SQL中,從表a中選擇全部,其中列a的值等於表b中最新條目的值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM