SQL SELECT语句中使用GROUP BY,并将所有值显示在一列中。

huangapple go评论107阅读模式
英文:

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

问题

以下是翻译好的部分:

所以我在我的MySQL中有一个用户表

| id | name |
|----|------|
| 1  | John |
| 2  | Matt |
| 3  | Matt |

我想要实现的是显示所有不重复的名字,并将其存储为PHP数组

我的查询

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

结果

| id | name |
|----|------|
| 1  | John |
| 3  | Matt |

通过上面的查询,我成功地通过排序最新的id来删除了重复项。但我要找的结果是这样的

|  all_name |
|-----------|
| John, Matt|

有没有办法获得上面的结果?我是MySQL的新手,希望你们能帮助我。谢谢!

注意:我已将代码部分保留在原文中,不进行翻译。

英文:

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!

答案1

得分: 3

SELECT GROUP_CONCAT(DISTINCT name ORDER BY name SEPARATOR ', ') AS names
FROM user

英文:
SELECT GROUP_CONCAT(DISTINCT name ORDER BY name SEPARATOR ', ') AS names
FROM `user`

huangapple
  • 本文由 发表于 2023年5月25日 12:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定