我有一个HTML表,其中显示名字...和一个人的课程,问题是,当一个人在数据库中有一个以上的课程(例如3个课程)时,循环将连续写入
alex alexia ... ... course 1
alex alexia ... ... course 2
alex alexia... ... course 3
如果可以帮助我将课程和名称分组显示在同一行中,因为如果我使用group by可以显示一个名称,但是仅显示一门课程(并非全部) 我试图通过在表Personale上使用标志列来完成此操作,如果该行写了一行,但设置为1,则该列不起作用
$formazione=mysqli_query($conn,"SELECT Formazione.Data_Formazione,Personale.*,Corso.* FROM Formazione NATURAL JOIN Personale NATURAL JOIN Corso ORDER BY Personale.Nome ASC;");
while (($row2 = mysqli_fetch_assoc($formazione))){
$flagPersonale=$row2['Flag_Personale'];
$idPersonale=$row2['ID_Personale'];
$aggFormazione=$row2['Aggiornamento_Formazione'];
$nomeCorso=$row2['Nome_Corso'];
$dataFormazione=$row2['Data_Formazione'];
$nome=$row2["Nome"];
$cognome=$row2["Cognome"];
$ruolo=$row2["Ruolo"];
$plesso=$row2["Plesso"];
$flagCorso=$row2["Flag_Corso"];
$nomEcogn=$nome+$cognome;
if($flagPersonale==0){
$inserimento = "UPDATE Personale SET Flag_Personale = 1
WHERE ID_Personale = $idPersonale";
if(mysqli_query($conn, $inserimento)) {
echo "<tr><td class=\"$nome\" id=\"$nome\">";
echo "<input id=\"$nomEcogn\" type=\"text\" class =\"it\" value=\"$nome\"
readonly=\"readonly\"></td><td><input type=\"text\" class =\"it\"
value=\"$cognome\" readonly=\"readonly\"></td><td><input type=\"text\"
class =\"it\" value=\"$ruolo\" readonly=\"readonly\"></td><td><input
type=\"text\" class =\"it\" value=\"$plesso\" readonly=\"readonly\"></td>
<td><input type=\"text\" class =\"it\" value=\"$nomeCorso\"
readonly=\"readonly\"> <button id=\"modifica\"><button id=\"Elimina\"></td>
</tr>";
}
else {
echo" mysqli_connect_error()";
}
}
我只想在单行中显示alex alexia ... ...课程1,course2,course3,谢谢!
答案 0 :(得分:0)
对于MySQL,请考虑使用GROUP_CONCAT
函数进行汇总查询,该函数可以返回项目列表。请调整您的查询到以下规格。请正确遵守GROUP BY
的SQL规则(取决于设置,MySQL可能会有所不同)(即遵循ONLY_FULL_GROUP_BY
设置)。
SELECT p.name, p.surname,
GROUP_CONCAT(course SEPARATOR ',') AS course_list
FROM persons p
JOIN courses c
ON p.person_id = c.person_id
GROUP BY p.name, p.surname
这可能涉及加入如上所述的单位级别查询。
SELECT f.Data_Formazione, p.*, agg.course_list
FROM Formazione f
NATURAL JOIN Personale p
INNER JOIN
(SELECT c.person_id, GROUP_CONCAT(course SEPARATOR ',') AS course_list
FROM courses c ON
GROUP BY c.person_id
) AS agg
ON agg.person_id = p.person_id
ORDER BY p.Nome ASC;
然后,在PHP中,您可以explode
以逗号分隔的课程列表到一个数组中:
$courses_array = explode(",", $sql_data['course_list']);