gpt4 book ai didi

php - 用逗号连接多行上的多个字段

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:57 25 4
gpt4 key购买 nike

我有 2 个表通过连接表连接。它们看起来像下面这样

      servers             serverInstances          instances
| id | ip | | id | sID | iID | | id | name |
|____|____________| |____|_____|_____| |____|______|
| 11 | 10.0.0.100 | | 1 | 11 | 40 | | 40 | real |
| 12 | 10.0.0.200 | | 2 | 11 | 41 | | 41 | fake |
| 3 | 12 | 45 | | 45 | test |

通过下面的查询我可以获得下面的数据

SELECT s.ip, i.name
FROM servers AS s
JOIN serverInstances AS si ON s.ID = si.sID
JOIN Instances AS i ON si.iID = i.ID


| ip | name |
|____________|______|
| 10.0.0.100 | real |
| 10.0.0.100 | fake |
| 10.0.0.200 | test |

我遇到的问题是获取上述信息并编写将返回以下内容的查询。

|     ip     | instances  |
|____________|____________|
| 10.0.0.100 | real, fake |
| 10.0.0.200 | test |

是否有一种简单而动态的方法来编写此查询?

最佳答案

正如 bwoebi 在评论中所说,group_concat 会给你这个。

SELECT s.ip,  group_concat(DISTINCT i.name ORDER BY i.name ASC SEPARATOR ", " ) as instances
FROM servers AS s
JOIN serverInstances AS si ON s.ID = si.sID
JOIN Instances AS i ON si.iID = i.ID
GROUP BY s.ip;

关于php - 用逗号连接多行上的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com