我上传按项目名称分组的图像。
在第一页上,我显示一个项目名称以及该组中的一张图像。
它显示了从该组图像中上传的第一个图像,而我正在尝试显示最后一个上载的图像。
我的代码是:
$dbhostname="localhost";
$dbusername="root";
$dbpassword="";
$db = "main_name";
$dbh = new PDO("mysql:host=$dbhostname;dbname=$db", $dbusername, $dbpassword);
foreach($dbh->query("SELECT *,COUNT(*)
FROM images
GROUP BY project_name ORDER BY img_timestamp DESC") as $row) {
echo "Project Name: " . $row['project_name'];
echo "<br>";
echo $row['imagelink'];
}
供您参考,我的MySQL表是:
Table name: images
id project_name imagelink img_timestamp
1 Travier image1 (timestamp of upload)
2 Travier image2 (timestamp of upload)
3 Travier image3 (timestamp of upload)
4 Travier image4 (timestamp of upload)
5 Collosion image1 (timestamp of upload)
6 Collosion image2 (timestamp of upload)
7 Collosion image3 (timestamp of upload)
帮助将不胜感激:)
最佳答案
您可以将A SUBQUERY
和MAX
用于:
SELECT id, project_name, COUNT(*),
MAX(img_timestamp) AS img_timestamp,
(SELECT imagelink FROM images img WHERE img.project_name = images.project_name ORDER BY img_timestamp DESC LIMIT 1) AS imagelink
FROM images GROUP BY project_name;
请记住,使用
*
会导致两列的名称分别为img_timestamp
和imagelink
,另一种方式是为时间戳和图像链接使用不同的别名。