MYSQL数组聚合函数,如PostgreSQL array_agg

问题描述 投票:4回答:3

我在MYSQL上有两个表,我想知道MYSQL上是否有任何聚合函数作为array_agg()FROM postgreSQL。

表1属性只有8条记录表2记录了捕获属性的记录,因此对于同一属性有时可以是1或n次,我得到了这个Qry:

SELECT p.id, pcb.users_admin_id as uid
FROM properties p
INNER JOIN prop_captured_by pcb ON p.id = pcb.property_id
-- GROUP BY p.id

id    uid
200   1
200   80
202   1
202   80
211   1
211   10
211   81
215   10 ...

如果我使用GROUP BY部分,我得到这个:

id    uid
200   1
202   1
211   1
215   10 ...

丢失除users_admin_id的第一个值之外的任何其他数据。我知道我可以通过postgreSQL中的array_agg()函数实现我想要的结果,但我无法弄清楚如何在MYSQL上做到这一点。

这是我的愿望结果:

id    uid
200   1,80 //an array, I don't mind about the separator, could be anything.
202   1,80
211   1,10,81
215   10 ...

我试过UNION,GROUP BY,INNER JOIN ......没有运气......有什么指针吗?

UPDATE

我正在使用这个家伙的many to many relations。希望它对其他人有用。我需要从第三个表添加用户名,因此最终查询如下所示:

SELECT p.id, group_concat(pcb.users_admin_id) as uid, group_concat(ua.name) as uin
FROM properties p
INNER JOIN prop_captured_by pcb ON p.id = pcb.property_id
INNER JOIN users_admin ua ON ua.id = pcb.users_admin_id
group by p.id;
mysql
3个回答
14
投票

你想用GROUP_CONCAT()之类的

SELECT p.id, group_concat(pcb.users_admin_id) as uid
FROM properties p
INNER JOIN prop_captured_by pcb 
ON p.id = pcb.property_id
group by p.id;

7
投票

我想你想要group_concat()

SELECT p.id, GROUP_CONCAT(pcb.users_admin_id) as uids
FROM properties p INNER JOIN
     prop_captured_by pcb
     ON p.id = pcb.property_id
GROUP BY p.id;

这会生成逗号分隔的字符串,但这与您在MySQL中获得的数组非常接近。


3
投票

MySQL 5.7.22引入了JSON_ARRAYAGG()JSON_OBJECTAGG()。既然你也想要用户名,你可以使用后者:

SELECT p.id, JSON_OBJECTAGG(pcb.users_admin_id, ua.name) as uin
FROM properties p
INNER JOIN prop_captured_by pcb ON p.id = pcb.property_id
INNER JOIN users_admin ua ON ua.id = pcb.users_admin_id
group by p.id;

DB Fiddle

© www.soinside.com 2019 - 2024. All rights reserved.