B
B
BigCrazyCat2018-08-17 16:05:54
MySQL
BigCrazyCat, 2018-08-17 16:05:54

How to select a parent and all children?

There is a table category :
5b76c64b3829e104050559.png
You need to select the parents and all child categories . I am using the following query:

SELECT t1.name AS parent, t2.name as children
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent_id = t1.id
WHERE t1.parent_id IS NULL
ORDER BY t1.id

Result:
5b76c7071cb96279963670.png
I would like to combine all the children into one element.
Example:
5b76c7e38fb7c811330269.png
How can this be implemented?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2018-08-17
@FanatPHP

I would like to combine all the children into one element.

This is not a question of sampling, but of processing the results.
The database is not responsible for the output format of the requested data.
In PHP, using PDO, for such a simple query, you can get a grouping by combining the FETCH_GROUP and PDO::FETCH_COLUMN modes.
But with a higher nesting level, or if you need to get any more data than the name, you will need to write the handler by hand.

A
ApeCoder, 2018-08-17
@ApeCoder

https://dev.mysql.com/doc/refman/8.0/en/with.html
recursive CTE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question