Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL SELECT with GROUP BY and show all values into a column

So I have user table in my MySQL

id name
1 John
2 Matt
3 Matt

What I want to achieve is showing all the names without duplicates and store it as an array in PHP

My query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$query = "SELECT * FROM user WHERE id IN (SELECT MAX(id) FROM user GROUP BY name)";

Result

id name
1 John
3 Matt

With the above query, I managed to remove the duplicates by sorting the newest id. But the result im looking for is this

all_name
John, Matt

Is there anyway to get the above result? I’m new to MySQL hope you guys can help me. Thanks!

>Solution :

SELECT GROUP_CONCAT(DISTINCT name ORDER BY name SEPARATOR ', ') AS names
FROM `user`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading