I need a SQL query for the following COMPLEX task…
I need to to select from a column named parent_id. If a row has 0 for parent_id it means that it’s a category (it also has the type column which says cat for category), if a row has 1 or more for parent_id it means that it is a rule. The parent_id of a rule, is the rule_id of a category.
The table structure with some data in it:

I need to select in a way, that EACH category, has its children under it. From the picture we would get this:
Sample Category 1
Sample rule 1
Sample Category 2
I tried some some queries that I found from here, but none worked.
This is what I tried last:
'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';
It returned Sample rule 1 only.
Ideas?
Try this fiddle http://sqlfiddle.com/#!2/0a9c5/16, sql code below
left out php-ization of code on purpose to maintain syntax highlighting, which seems not to work anyway
If you exceed maximum allowed group_concat size you can either increase it or use the following version, and do a bit more processing in php:
and in php, skeleton code provided only, fill in with the actual values, assuming you use pdo and your pdostatement var is named
$query:replace stuff between … with valid code