phpmysqlcodeignitergroup-bygroup-concat

Mysql query to GROUP BY a column and concatenate another column in each group with commas


I have two table maintenance_owner and maintenance_users there are my table structure bellow This is maintenance_users table enter image description here

and This is maintenance_owner table maintenance_users table

now i can get all user with this code

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

it returns

[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
    )

but i need to get the result like this

    [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
    )

I need to do this with an SQL query only; I'm using the codeigniter framework.


Solution

  • You can try this as you are using codeigniter there is a mysql function called GROUP_CONCAT learn more about it and you will understand

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