我正在尝试优化其中一个脚本。这是一个照片网站,使用WHILE WEND循环显示一个大网格图像,循环浏览我的DB(MySQL)照片表。
在这个循环中,我有另一个WHILE END循环,它从我的人员表中获取每张照片中人物的名字。
我的问题是,我可以通过在主查询中添加JOIN来丢失第二个WHILE WEND循环吗?
我的困惑来自于回来不止一个人。我无法弄清楚如何用逗号分隔一个或多个名字,我只是不知道。也许我的脚本很好,但是我确信没有嵌套循环可以更快,因为在某些时候,我正在考虑添加另一个查询,它返回每张照片的前5个关键字,并且不要我想添加另一个循环!
SCREEN SHOT
我的PSUEDO代码
Set rsPhotos = Conn.Execute(" " _
& "SELECT photoID, setID, caption, dateCreated, dateUploaded " _
& "FROM photos ORDER BY dateCreated DESC;)"
While NOT rsPhotos.EOF
Response.Write "<div>"
Response.Write "<img src=""photo.jpg"">"
Response.Write "<p>"
people_str = ""
Set rsPeople = Conn.Execute("SELECT p.person FROM photoPeople AS pp " _
& "LEFT JOIN people AS p USING (personID) " _
& "WHERE pp.photoID = "&rsPhotos.Fields("photoID")&" " _
& "ORDER BY p.person ASC;")
While NOT rsPeople.EOF
people_str = people_str & ", " & rsPeople.Fields("person")
rsPeople.MoveNext
Wend
rsPeople.Close
Response.Write Mid(people_str,3)
Response.Write "</p>"
Response.Write "<div>"
rsPhotos.MoveNext
Wend
rsPhotos.Close
DB SCHEMA
PHOTOS tbl
photoID | INT 9
setID | INT 9
caption | VARCHAR2000
dateCreated | DATETIME
dateUploaded | DATETIME
PHOTOPEOPLE tbl
photoID | INT 9
personID | INT 7
PEOPLE tbl
personID | INT 7
person | VARCHAR 100
答案 0 :(得分:4)
这应该这样做 -
SELECT photos.photoID, photos.setID, photos.caption, photos.dateCreated, photos.dateUploaded, GROUP_CONCAT(p.person ORDER BY p.person ASC SEPARATOR ', ')
FROM photos
LEFT JOIN photoPeople AS pp
ON photos.photoID = pp.photoID
LEFT JOIN people AS p
ON pp.personID = p.personID
GROUP BY photos.photoID
ORDER BY dateCreated DESC