Doee Doee - 29 days ago 5x
MySQL Question

Output all the elements grouped by in sql

I have created a table in phpmyadmin which has 2 columns one named marca and the other named categoria. I want to group these by marca. I create this sql query to do this but the problem is that it outputs only one category for marca.

$sql0="SELECT marca , categoria FROM marche GROUP BY marca ";

I want to group by marca and output in the row of this marca all the categories belonging to it. How is this possible? Thanks!


You can use GROUP_CONCAT for your needs,

$sql0="SELECT marca , GROUP_CONCAT(categoria) as category_group FROM marche GROUP BY marca ";

By default you should get a comma-separated list of elements in category_group. You can use the PHP explode function to turn that into an array in your PHP logic.