mysql 数组函数,MYSQL数组聚合函数,例如PostgreSQL array_agg

I got two tables on MYSQL, I wonder if there is any aggregate function on MYSQL as array_agg() FROM postgreSQL.

TABLE 1 properties Only have 8 records

TABLE 2 records who captured the property, so sometimes can be 1 or n times for the same property, and I got this 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 ...

If I use the GROUP BY part I get this:

id uid

200 1

202 1

211 1

215 10 ...

Losing any other data than the first value for users_admin_id. I know that I can achieve my desired result with array_agg() function from postgreSQL but I can't figured out how to do it on MYSQL.

This is my desire Result:

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 ...

I have tried UNION, GROUP BY, INNER JOIN... no luck...

Any pointers?

UPDATE

I am using the many to many relations from this guy. Hopes it is useful for someone else. I needed to add the user's name from a third table, so the final query looks like this:

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;

解决方案

You want to use GROUP_CONCAT() like

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值