mysql表单子数组(数组聚合)并返回

时间:2018-12-06 05:35:31

标签: mysql arrays aggregate sub-array

我有以下mysql查询

    select  m.flat_id,
            f.flat_no,
            fo.owner_name,
            oc.occupant_name,
            b.block_name,
            f.floor_no,
            f.floor_id,
            m.user_id as user_map_id

    from svk_apt_flats_users_mapping m
    left join svk_apt_users u on u.user_id = m.user_id and u.association_id = 2 
        and u.customer_id = 2 and u.is_active = 1 and u.user_id is not null
    left join svk_apt_flats f on f.flat_id = m.flat_id and f.is_active = 1
    left join svk_apt_blocks b on b.block_id = f.block_id and b.is_active = 1
    left join svk_apt_flat_owners fo on u.user_role_type_id = 4 and fo.is_active = 1 and fo.user_id = m.user_id
    left join svk_apt_occupants oc on u.user_role_type_id = 5 and oc.is_active = 1 and oc.user_id = m.user_id 

where   f.block_id = 3
        and m.user_id <> 2
        and m.customer_id = 2
        and m.association_id = 2 
        and m.is_active = 1
        and m.is_active = 1
        and (case when m.user_role_type_id = 5 then true else m.is_approved = 1 end)

和输出: enter image description here

我想将具有相同“ user_map_id”的行聚合为一行。 mysql中有什么解决方案吗?

1 个答案:

答案 0 :(得分:0)

使用分组依据

    select  m.flat_id,
            f.flat_no,
            fo.owner_name,
            oc.occupant_name,
            b.block_name,
            f.floor_no,
            f.floor_id,
            m.user_id as user_map_id

    from svk_apt_flats_users_mapping m
    left join svk_apt_users u on u.user_id = m.user_id and u.association_id = 2 
        and u.customer_id = 2 and u.is_active = 1 and u.user_id is not null
    left join svk_apt_flats f on f.flat_id = m.flat_id and f.is_active = 1
    left join svk_apt_blocks b on b.block_id = f.block_id and b.is_active = 1
    left join svk_apt_flat_owners fo on u.user_role_type_id = 4 and fo.is_active = 1 and fo.user_id = m.user_id
    left join svk_apt_occupants oc on u.user_role_type_id = 5 and oc.is_active = 1 and oc.user_id = m.user_id 

where   f.block_id = 3
        and m.user_id <> 2
        and m.customer_id = 2
        and m.association_id = 2 
        and m.is_active = 1
        and m.is_active = 1
        and (case when m.user_role_type_id = 5 then true else m.is_approved = 1 end)
group by u.user_role_type_id;

如果您未在其上指定诸如SUM,AVG等聚合函数,则MySQL将为所有列选择第一行的值