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
$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`