我有一个查询数据库以获取最新曲目的 mysql 语句。但是,由于数据库是部分规范化的,因此 ID 位于不同的表中。在查询中,我从艺术家表中获取艺术家 ID 并将它们放入变量中。然后将变量解析为一个查询,该查询查看曲目以找到最新的曲目,这就是问题所在。由于 $artist 变量可以包含大量 ID,所有这些 ID 都被解析到查询中,即使我在查询中设置了 LIMIT,结果也是几个 url 放在一起。
请记住,我无法限制艺术家查询,因为我需要从表中获取所有艺术家并从所有艺术家中找到最新的曲目。
如何在不限制艺术家查询的情况下从查询中获取最新的 url?
//Set up artist query so only NBS artists are chose
$findartist = mysql_query("SELECT * FROM artists") or die(mysql_error());
while ($artist = mysql_fetch_array($findartist)){
$artist = $artist['ID'];
//get track url
$fetchurl = mysql_query("SELECT * FROM tracks WHERE id = '$artist' ORDER BY timestamp DESC LIMIT 1");
url = mysql_fetch_array($fetchurl);
$track_ID = $url ['ID'];
$trackname = $url ['name'];
$trackurl = $url ['url'];
$artist_ID =$url['ID'];
}
添加:
$findartist = mysql_query("SELECT A.*, T.*
FROM (
SELECT T.ARTIST_ID, MIN(T.TRACK_ID) TRACK_ID
FROM (
SELECT ARTIST_ID, MAX(`TIMESTAMP`) `TIMESTAMP`
FROM TRACKS
GROUP BY ARTIST_ID
) L
JOIN TRACKS T ON ( L.ARTIST_ID = T.ARTIST_ID
AND L.`TIMESTAMP` = T.`TIMESTAMP`)
GROUP BY T.ARTIST_ID
) X
JOIN ARTISTS A ON X.ARTIST_ID = A.ARTIST_ID
JOIN TRACKS T ON (X.TRACK_ID = T.TRACK_ID AND X.ARTIST_ID = T.ARTIST_ID)
ORDER BY A.NAME");
while ($artist = mysql_fetch_array($findartist)){
$artist = $artist['ID'];
$trackurl = $artist['url'];