MYSQL array aggregate function like PostgreSQL array_agg

后端 未结 3 1008
青春惊慌失措
青春惊慌失措 2020-12-06 10:55

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 record

相关标签:
3条回答
  • 2020-12-06 11:15

    MySQL 5.7.22 introduced JSON_ARRAYAGG() and JSON_OBJECTAGG(). Since you want the user name as well, you could use the latter:

    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

    0 讨论(0)
  • 2020-12-06 11:19

    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)
  • 2020-12-06 11:36

    I think you want 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;
    

    This produces a comma-delimited string, but that is as close to an array that you get in MySQL.

    0 讨论(0)
提交回复
热议问题