我需要针对以下复杂任务的 SQL 查询...
我需要从名为 parent_id
的列中进行选择。如果某行的 parent_id
为 0,则表示它是一个类别(它还有 type
列,其中显示 cat
表示类别),如果行有 1 个或多个 parent_id
这意味着它是一个规则。一个规则的parent_id
,就是一个类别的rule_id
。
包含一些数据的表结构:
我需要以某种方式选择,每个类别下都有其子项。从图片中我们会得到这个:
Sample Category 1
Sample rule 1
Sample Category 2
我尝试了一些从这里找到的查询,但都没有用。
这是我最后尝试的:
'SELECT *
FROM ' . RULES_TABLE . ' AS parent
LEFT JOIN ' . RULES_TABLE . ' AS child
ON child.parent_id = parent.rule_id
WHERE parent.parent_id = 0
AND parent.public = 1
ORDER BY parent.cat_position, child.rule_position';
它仅返回示例规则 1。
想法?
最佳答案
试试这个 fiddle 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 ...
}
用有效代码替换...之间的内容
关于php - 选择并列出 child 和 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770436/