2

我正在尝试优化其中一个脚本。它用于库存照片网站,并使用 WHILE WEND 循环显示大量图像,循环通过我的 DB (MySQL) 照片表。

在这个循环中,我有另一个 WHILE END 循环,它从我的人物表中获取每张照片中人物的姓名。

我的问题是,我可以通过向主查询添加 JOIN 来丢失第二个 WHILE WEND 循环吗?

我的困惑来自于返回多个人。我不知道如何用逗号分隔一个或多个名称,我只是不知道。也许我的脚本本来就很好,但我确信没有嵌套循环它会更快,因为在某些时候,我正在考虑添加另一个查询,它返回每张照片的前 5 个关键字,并且不要不想添加另一个循环!

截屏

在此处输入图像描述

我的伪代码

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

数据库架构

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
4

1 回答 1

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

GROUP_CONCAT()

于 2012-04-08T22:37:13.860 回答