2012-08-14 121 views
1

我有两张表,歌曲和历史记录。歌曲表如下所示: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,但没有奏效。有任何想法吗?

回答

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

+0

谢谢!我会接受它作为答案,当它让我! – austinhollis 2012-08-14 17:03:24

0

入住这

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

我的事情该查询解决您的问题

+0

不,这只会做两个表的完整笛卡尔积 – 2012-08-14 17:02:16

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的内容作为外键。

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

但它会更好,如果你组织你的表由维奈的建议。