我遇到了这个问题:
我有两张桌子:样本和歌曲 我想选择
pathName from samples
id_user from samples
id from songs
name from songs
每个样本都属于一首歌:我想将每个共享相同歌曲ID的样本分组,以便选择最后一个日期。 所以我在这两个表之间进行连接:
$query = 'SELECT
samples.pathName path_name,
samples.id_user id_user,
songs.id id_song,
songs.name song_name
FROM (SELECT *, MAX(date) AS maxDate FROM samples GROUP BY id_song ORDER BY maxDate) samples
INNER JOIN songs songs
ON songs.id = samples.id_chanson
WHERE songs.finished = false';
它不应该那么重,我希望我很清楚......:)
答案 0 :(得分:3)
尝试:
SELECT sa.pathName,
sa.id_user,
so.id id_song,
so.name song_name
FROM songs so
JOIN (SELECT id_song, MAX(`date`) AS maxDate FROM samples GROUP BY id_song) mx
ON so.id = mx.id_song
JOIN samples sa
on mx.id_song = sa.id_song and mx.maxDate = sa.`date`
WHERE so.finished = 'false'
ORDER BY mx.maxDate
答案 1 :(得分:0)
我会用这样的东西:
SELECT
samples.pathName path_name,
samples.id_user id_user,
songs.id id_song,
songs.name song_name
FROM
samples INNER JOIN songs ON songs.id = samples.id_song
WHERE
songs.finished = false
AND (samples.id_song, samples.`date`) IN (SELECT id_song, MAX(`date`)
FROM samples
GROUP BY id_song)