试试这个小提琴http://sqlfiddle.com/#!2/0a9c5/16,下面的 sql 代码
SELECT c.rule_id, c.rule_title, GROUP_CONCAT(r.rule_title)
FROM RULES_TABLE AS c
LEFT JOIN RULES_TABLE AS r
ON r.parent_id = c.rule_id
WHERE c.parent_id IS NULL AND c.public = 1
GROUP BY c.rule_id
ORDER BY c.cat_position, c.rule_position;
故意省略代码的 php 化以保持语法突出显示,这似乎无论如何都不起作用
如果超过允许的最大 group_concat 大小,您可以增加它或使用以下版本,并在 php 中进行更多处理:
SELECT c.rule_id, c.rule_title, r.rule_title as r_rule_title
FROM RULES_TABLE AS c
LEFT JOIN RULES_TABLE AS r
ON r.parent_id = c.rule_id
WHERE c.parent_id IS NULL AND c.public = 1
ORDER BY c.cat_position, c.rule_position;
并且在 php 中,仅提供骨架代码,填写实际值,假设您使用 pdo 并且您的 pdostatement var 命名为$query
:
$old_rule_id = null;
$rrt = array(); // will contain all r.rule_titles for a give c.rule_id
while( ($i = $query->fetch(PDO::FETCH_OBJ)) !== false ) {
if( $old_rule_id != $i->rule_id ) {
if( count($rrt) ) {
echo ... all the data for previous rule from $rrt ...
echo ... end of previous element ...
$rrt = array(); // empty it to collect new data
}
echo ... start of current element use data from $i->rule_id and $i->rule_title ...
$old_rule_id = $rule_id;
}
$rrt[] = $i->r_rule_title;
}
// the following is the same if from inside the while, minus reinitialization of $rrt;
if( count($rrt) ) {
echo ... all the data for previous rule from $rrt ...
echo ... end of previous element ...
}
用有效代码替换...之间的东西