Mysql 查询 GROUP BY 列并用逗号连接每组中的另一列

问题描述 投票:0回答:1

我有两张桌子

maintenance_owner
maintenance_users
下面是我的表结构 这是maintenance_users表

和 这是maintenance_owner表

现在我可以使用此代码获取所有用户

    $this->db->select('mu.*, mo.id_land_owner as mu_owner, mo.group_name, mo.id_mu');
    $this->db->from('maintenance_users as mu');
    $this->db->join('maintenance_owner as mo','mu.id_maintenance = mo.id_mu');
    $this->db->where('mo.id_land_owner', $land_owner_id);
    return $this->db->get()->result();

它回来了

[0] => stdClass Object
    (
        [id_maintenance] => 170
        [full_name] => 
        [username] => [email protected]
        [password] => 
        [token] => 914c001251a1ab018e5eb51923e8f6cc
        [mu_owner] => 152
        [group_name] => Cleaner
        [id_mu] => 170
    )

[1] => stdClass Object
    (
        [id_maintenance] => 176
        [full_name] => 
        [username] => [email protected]
        [password] => 
        [token] => 579faa456520656fcc24be047ca6a3bf
        [mu_owner] => 152
        [group_name] => 
        [id_mu] => 176
    )

[2] => stdClass Object
    (
        [id_maintenance] => 175
        [full_name] => 
        [username] => [email protected]
        [password] => 
        [token] => d2f6b180a6a7bb32ecd26ffe0297f8f5
        [mu_owner] => 152
        [group_name] => 
        [id_mu] => 175
    )

但我需要得到这样的结果

    [0] => stdClass Object
    (
        [id] => 30
        [id_land_owner] => 152
        [group_name] => Cleaner
        [group_users] => [email protected],[email protected],[email protected],[email protected]
    )

[1] => stdClass Object
    (
        [id] => 29
        [id_land_owner] => 152
        [group_name] => Gardener
        [group_users] => [email protected],[email protected],[email protected]
    )

我只需要使用 SQL 查询来完成此操作;我正在使用 codeigniter 框架。

php mysql codeigniter group-by group-concat
1个回答
1
投票

您可以尝试这个,因为您正在使用 codeigniter mysql 有一个函数叫做

GROUP_CONCAT
了解更多你就会明白

    $this->db->select('mo.id, mo.id_land_owner as id_land_owner, mo.group_name, GROUP_CONCAT(mu.username SEPARATOR ",") as group_users', false);
    $this->db->from('maintenance_users as mu');
    $this->db->join('maintenance_owner as mo','mu.id_maintenance = mo.id_mu');
    $this->db->group_by('mo.group_name'); 
    $this->db->where('mo.id_land_owner', 152);
    return $this->db->get()->result();
© www.soinside.com 2019 - 2024. All rights reserved.