1

我有两张桌子,歌曲和历史。歌曲表如下所示:

ID | title      | artist      | duration
1  | some title | some artist | 83592

历史表如下所示:

ID | title      |   artist    | duration | date_played
5  | some title | some artist | 83592    | 2012-08-08 11:22:00

如果历史表中最新条目中的标题和艺术家匹配,我将如何从歌曲表中回显 ID?

我试过SELECT * FROM history JOIN songs ON title=songs.title AND artist=songs.artist ORDER BY date_played DESC LIMIT 0, 1了,但没有用。有任何想法吗?

4

5 回答 5

3
SELECT s.ID
FROM songs s
INNER JOIN (SELECT * FROM history h ORDER BY date_played DESC LIMIT 1) lastHistory
ON lastHistory.title = s.title AND lastHistory.artist = s.artist

( Sqlfiddle )

于 2012-08-14T16:58:28.040 回答
2
SELECT * FROM history A INNER JOIN songs B 
ON A.title=B.title AND A.artist=B.artist 
ORDER BY A.date_played DESC

我的建议是在历史表中,您可以使用歌曲表的歌曲 ID 而不是艺术家和标题。

表:歌曲

ID | title      | artist      | duration
1  | some title | some artist | 83592

表:历史

ID | songid  | date_played
5  | 1       | 2012-08-08 11:22:00

这样您就可以在架构中进行一些优化。

然后你可以试试这个查询。

SELECT * FROM history A INNER JOIN songs B 
ON A.songid=B.ID ORDER BY A.date_played DESC
于 2012-08-14T17:10:03.833 回答
1
SELECT songs.* 
FROM songs, (SELECT * FROM history ORDER BY DESC date_played LIMIT 1) hist_view
WHERE songs.title = hist_view.title 
    AND songs.artist = hist_view.artist

上面的查询创建了最近播放的名为 hist_view 的歌曲的内联视图(使用 LIMIT 和 ORDER BY DESC)。然后它与歌曲表结合,根据艺术家和标题查找匹配的歌曲。

我建议你在历史表中添加类似 song_id 的东西作为外键。

于 2012-08-14T17:08:48.743 回答
1

您可以使用

SELECT   songs.id
FROM     songs,
         history
WHERE    songs.title = history.title
AND      songs.artist = history.artist
ORDER BY history.date_played DESC

或者

SELECT     songs.id
FROM       songs
INNER JOIN history ON  history.title = songs.title
                   AND history.artist = songs.artist
ORDER BY   history.date_played DESC

但如果你按照 Vinay 的建议组织你的桌子会更好。

于 2012-08-14T19:03:25.600 回答
0

检查这个

select songs1.id,history1.title,history1.artist 
from songs as songs1,history as history1
order by date_diplayed desc

我认为这个查询可以解决您的问题

于 2012-08-14T16:57:14.733 回答