通过列数据获取SQL查询结果组

时间:2019-06-12 16:59:27

标签: php mysql codeigniter relational-database

我有两个表maintenance_ownermaintenance_users 我的桌子结构下面 这是maintenance_users表 enter image description here

和 这是maintenance_owner表 maintenance_users table

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

    $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] => abt2050+m3@gmail.com
        [password] => 
        [token] => 914c001251a1ab018e5eb51923e8f6cc
        [mu_owner] => 152
        [group_name] => Cleaner
        [id_mu] => 170
    )

[1] => stdClass Object
    (
        [id_maintenance] => 176
        [full_name] => 
        [username] => bii@fatafati.net
        [password] => 
        [token] => 579faa456520656fcc24be047ca6a3bf
        [mu_owner] => 152
        [group_name] => 
        [id_mu] => 176
    )

[2] => stdClass Object
    (
        [id_maintenance] => 175
        [full_name] => 
        [username] => iamnow78+m4@gmail.com
        [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] => abt2050+m1@gmail.com,abt2050+m2@gmail.com,abt2050+m3@gmail.com,abt2050+m4@gmail.com
    )

[1] => stdClass Object
    (
        [id] => 29
        [id_land_owner] => 152
        [group_name] => Gardener
        [group_users] => abt2050+a1@gmail.com,abt2050+a2@gmail.com,abt2050+a3@gmail.com
    )

仅需要使用sql查询来执行此操作 我正在使用Codeigniter框架

1 个答案:

答案 0 :(得分:1)

您可以在使用codeigniter时尝试此操作 有一个名为GROUP_CONCAT的mysql函数 详细了解它,您将了解

    $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();