I know this question comes up often, but today I can\'t find the answer I\'m looking for. I have a table with this schema.
CREATE TABLE `comments` (
`id`
I've not saying exactly, i think your getting this kind of problem as following as:
Ordered_Item
ID | Item_Name
1 | Pizza
2 | Stromboli
Ordered_Options
Ordered_Item_ID | Option_Number | Value
1 43 Pepperoni
1 44 Extra Cheese
2 44 Extra Cheese
Output
ID | Item_Name | Option_1 | Option_2
1 Pizza Pepperoni Extra Cheese
2 Stromboli NULL Extra Cheese
And the my suggestions to use this method resolve this problem as there following as:
select ordered_item.id as `Id`, ordered_item.Item_Name as `ItemName`, GROUP_CONCAT(Ordered_Options.Value) as `Options` from ordered_item, ordered_options where ordered_item.id=ordered_options.ordered_item_id group by ordered_item.id
Which would output:
Id ItemName Options
1 Pizza Pepperoni,Extra Cheese
2 Stromboli Extra Cheese
That way you can have as many options as you want without having to modify your query.
Ah, if you see your results getting cropped, you can increase the size limit of GROUP_CONCAT like this:
SET SESSION group_concat_max_len = 8192;
Are you looking for
SELECT p.id, child.*
FROM comments p
INNER JOIN comments child ON (child.parent_id = p.id)
WHERE ....
UPDATE
Or LEFT JOIN
if you want to see rows with no parents
Parents are records with no parent_id
.
Children have parent_id
equal to the parent comment's id
.
SELECT ...
FROM comments AS parent
LEFT JOIN comments AS child
ON child.parent_id = parent.id
WHERE parent.parent_id IS NULL
ORDER BY parent.id, child.id;
Note that the self-join should be an outer join so that you don't miss parent comments with no children.