我的数据库中有以下表格:
CREATE TABLE subjects (
subject_id int(11) NOT NULL AUTO_INCREMENT,
subject text,
PRIMARY KEY (subject_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE users_subjects (
users_subjects_id int(11) NOT NULL AUTO_INCREMENT,
user_id_fk int(11),
subject_id_fk int(11),
FOREIGN KEY(user_id_fk) REFERENCES users(id),
FOREIGN KEY(subject_id_fk) REFERENCES subjects(subject_id),
PRIMARY KEY (users_subjects_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;
在表“ users_subjects”中,我将表“ subjects”和“ users”相关联。
所有表数据都是通过PHP引入的,当引入user
和subjects
时,会创建'users_subjects
'表。
例如,如果我输入一个ID为1的名为“ EXAMPLE”的用户,ID为1和2的SAT和ICT主题,则“ users_subjects
”表将类似于以下内容:
问题是我试图在PHP表中向用户显示他们的相应主题,但是我不知道如何在“主题”列中显示以逗号分隔的主题。我想做类似下图的操作。有人能帮我吗?谢谢
这就是我的代码中的内容:
<table class="users">
<tr>
<th colspan="2"><h2>USERS</h2></th>
</tr>
<tr>
<th> NAME </th>
<th> SUBJECTS </th>
</tr>
<?php
$sql = "SELECT * FROM users WHERE rol='profesor'";
$result = $conn->query($sql); if ($result->num_rows==0){
echo 'No users';
}else{
while($row = $result->fetch_assoc()) {
$subjects = "";
$sql2 = "SELECT user_id_fk, GROUP_CONCAT(subject_id_fk SEPARATOR ',') FROM users_subjects WHERE user_id_fk='$id' GROUP BY user_id_fk;";
/*$sql2 = "SELECT user_id_fk, GROUP_CONCAT(subject_id_fk SEPARATOR ',') FROM users_subjects where user_id_fk='$id'";*/
$result2 = $conn->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$subjects = $row2["subject"];
}
echo "<tr>
<td>".$row["username"]."</td>
<td>".$subjects."</td></tr>";
}
}
?>
</table>
答案 0 :(得分:1)
您需要的查询必须包含分组才能使用GROUP_CONCAT
:
SELECT user_id_fk, GROUP_CONCAT(subject_id_fk SEPARATOR ',')
FROM users_subjects
WHERE user_id_fk=?
GROUP BY user_id_fk
如果要获取名称,则需要JOIN
:
SELECT users.username, GROUP_CONCAT(subjects.subject SEPARATOR ',')
FROM users_subjects
RIGHT JOIN users ON users.id=users_subjects.user_id_fk
RIGHT JOIN subjects ON subjects.subject_id=users_subjects.subject_id_fk
WHERE user_id_fk=?
GROUP BY user_id_fk