0

我正在尝试multiple rows in sql在单个表格框中显示数据。格式为:

"MovieTitle" "movieReleaseYear" "directorName"

The Matrix      1999             Andy Wachowski, Lana Wachowski

whereAndy Wachowski and Lana Wachowski来自不同的行,但聚集在一起group_concat

我在 phpmyadmin 中获取它们没有问题,但我不知道如何在 php 中显示它。

我有这个:

$sql="SELECT 725G54_5_movies.MovieTitle, 725G54_5_movies.movieProductionYear,      GROUP_CONCAT( 725G54_5_director.directorName ) 
                    FROM 725G54_5_movies
                    JOIN 725G54_5_directed ON 725G54_5_movies.MovieID = 725G54_5_directed.movieID
                    JOIN 725G54_5_director ON 725G54_5_directed.directorID = 725G54_5_director.directorID
                    GROUP BY 725G54_5_movies.MovieTitle
                    ORDER BY $order ASC";
                $result=mysql_query($sql);  

                //Presentation av kontakterna via while-sats till ett formulär
                while($rows=mysql_fetch_array($result)){

                echo "<tr>
                <td>"; echo $rows['MovieTitle']; echo "</td>
                <td>";  echo $rows['movieProductionYear']; echo "</td>
                <td>"; 
                    while($director=mysql_fetch_array($rows['directorName'])){ echo $director; }; 
                    echo"</td>
                </tr>";
4

2 回答 2

1

Group Concat 已经连接了董事的名字,所以你不需要迭代$rows['directorName']。你的代码 id 中的这部分错误,因为$rows是查询结果中的一行并且$rows['director']是该行中的一个值,你不能迭代一个值。

 $sql = "SELECT GROUP_CONCAT( 725G54_5_director.directorName ) AS directorNames ..."

while($rows=mysql_fetch_array($result)){

                echo "<tr>";
                echo "<td>" . $rows['MovieTitle'] . "</td>";
                echo "<td>" . $rows['movieProductionYear'] . "</td>"
                echo "<td>" . $rows['directorNames'] . "</td>" 
                echo"</tr>";
}

您使用的GROUP BY 725G54_5_movies.MovieTitlesodirectorNames字段将是directorName此 Movie 的所有连接的结果。

于 2013-05-24T09:55:32.877 回答
0

关键信息是您需要为您的 GROUP_CONCAT 设置别名,以便您可以在数组中访问它。在输出 html 块时,我也会使用 Heredoc 以提高可读性:

$sql=
"SELECT
    725G54_5_movies.MovieTitle,
    725G54_5_movies.movieProductionYear,
    GROUP_CONCAT(725G54_5_director.directorName) directorNames
FROM
    725G54_5_movies
    JOIN
    725G54_5_directed
    ON 725G54_5_movies.MovieID = 725G54_5_directed.movieID
    JOIN
    725G54_5_director
    ON 725G54_5_directed.directorID = 725G54_5_director.directorID
GROUP BY
    725G54_5_movies.MovieTitle
ORDER BY
    $order ASC";

$result=mysql_query($sql);

//Presentation av kontakterna via while-sats till ett formulär
echo "<table>";
while($rows=mysql_fetch_array($result)){
    echo <<<HTML
        <tr>
            <td>{$rows['MovieTitle']}</td>
            <td>{$rows['movieProductionYear']}</td>
            <td>{$rows['directorNames']}</td>
        </tr>
HTML;
}
echo "</table>";
于 2013-05-24T10:05:57.713 回答