2012-08-14 119 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 

但它會更好,如果你組織你的表由維奈的建議。