简体   繁体   中英

Apply distinct on join query with CodeIgniter Query Builder

I am trying to make a query with codeigniters Query Builder

$this->db->select('*')
            ->from('users')
            ->join('user_to_group', 'users.id=user_to_group.user_id')
            ->where('user_to_group.group_id !=', $group->id);

Here in above code I'm trying to fetch records of users which are not in provided group. This query is working fine at the stage but sometimes it returns same record multiple times as a user can be part of multiple groups. So to overcome this problem I want to apply distinct to this query.

But I don't find the correct way to do it.

Please help..

You need to add group_by in query.

Write your query as below:-

 $this->db->select('*')
          ->from('users')
          ->join('user_to_group', 'users.id=user_to_group.user_id')
          ->where('user_to_group.group_id !=', $group->id)
          ->group_by('users.id'); // add this line

Note : this query will work in only case if you use "user_to_group" table as multiple relation table mean user and group both tables id you used in this third table name "user_to_group".

Use group by if you need unique record on base of group_id Try this :

$this->db->select('*')
            ->from('users')
            ->join('user_to_group', 'users.id=user_to_group.user_id')
            ->where('user_to_group.group_id !=', $group->id)
        ->group_by("user_to_group.group_id");

Because you will get multiple record when user is part of multiple group so you will use this to get groups unique records user vise or you will apply both group_id and user_id in group_by to get it unique from both field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM