PHP MySQL连接两个表

时间:2012-08-14 16:53:14

标签: php mysql

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

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但是没有用。有什么想法吗?

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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的内容作为外键。

答案 3 :(得分: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的建议组织你的桌子会更好。

答案 4 :(得分:0)

检查

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

我这个查询解决了你的问题