我认为这可能比SQL更像是PHP,因为我的结果是正确的。关于如何实现我需要的格式,我的想法是空白的。
我有两张桌子:
privilege;
+--------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+---------------------+------+-----+---------+----------------+
| privilege_id | bigint(20) | NO | PRI | NULL | auto_increment |
| privilege_group_id | bigint(20) | NO | | NULL | |
| privilege_name | varchar(255) | NO | | NULL | |
+--------------------+---------------------+------+-----+---------+----------------+
privilege_group;
+----------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+--------------+------+-----+---------+----------------+
| privilege_group_id | bigint(20) | NO | PRI | NULL | auto_increment |
| privilege_group_name | varchar(255) | NO | | NULL | |
+----------------------+--------------+------+-----+---------+----------------+
我需要输出我的查询的请求,如下所示:
权限组名称
另一个权限组名称
我的查询返回正确的结果:
SELECT privilege_group.privilege_group_name, privilege.privilege_name FROM privilege LEFT JOIN privilege_group ON privilege.privilege_group_id = privilege_group.privilege_group_id ORDER BY privilege_group.privilege_group_id ASC
我不太确定如何在每个孩子的第一个结果之后忽略特权组名称。例如我明白了:
权限组名称
权限组名称
另一个权限组名称
另一个权限组名称
我知道我可以通过循环2次查询来实现这一点,但上面的内容返回了正确的数据,而我却无法知道如何处理它!
编辑:
<?php
try {
$rnum = '';
$stmt = $dbh->prepare("SELECT privilege_group.privilege_group_name,privilege.privilege_name
FROM privilege
LEFT JOIN privilege_group ON privilege.privilege_group_id = privilege_group.privilege_group_id
ORDER BY privilege_group.privilege_group_id ASC");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rnum++;
// I know I need some conditional around this to only show it once per group!
if () {
echo "<b>$row[privilege_group_name]</b><br />";
//
}
echo "$row[privilege_name]<br />";
}
}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}
?>
答案 0 :(得分:0)
首先,将privilege_group.privilege_group_id
添加到您的SELECT
语句中,然后:
<?php
try {
$stmt = $dbh->prepare(
"SELECT privilege_group.privilege_group_id,
privilege_group.privilege_group_name,
privilege.privilege_name
FROM privilege
LEFT JOIN privilege_group ON
privilege.privilege_group_id = privilege_group.privilege_group_id
ORDER BY privilege_group.privilege_group_id ASC");
$last_group_id = -1;
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($last_group_id != $row['privilege_group_id']) {
echo "<b>" . $row['privilege_group_name'] . "</b><br />";
$last_group_id = $row['privilege_group_id'];
}
echo $row['privilege_name'] . "<br />";
}
} catch(PDOException $e) {
echo 'Error : '. $e->getMessage();
exit();
}
?>