codeigniter中的多个连接和分组

时间:2015-05-14 15:43:41

标签: sql codeigniter group-by

我正在使用Codeigniter,我想要做的是一个按组返回用户的查询。

一个组可以有一个或多个用户,这里是表格的例子:

groups table        users table              users_by_groups table
    id                  id                    id_group   id_user
    1                   10                      1          10
    2                   11                      1          11
    3                   12                      1          12
                                                2          11
                                                3          12

我做的查询:

public function getUsersByGroup(){
        $this->db->select('g.vgro_name,u.vusr_user');
        $this->db->from('vts_user_by_group b');
        $this->db->join('vts_groups g', 'b.vubg_vgro_id = g.vgro_id');
        $this->db->join('vts_users u', 'b.vubg_vusr_id = u.vusr_id');
        $this->db->group_by('g.vgro_name,vusr_user');
        // $this->db->order_by('u.vusr_user','asc');
        $query = $this->db->get();
        return $query->result();
    }

这是什么回归:

      0 => 
object(stdClass)[28]
  public 'vgro_name' => string 'GROUP1' (length=4)
  public 'vusr_user' => string 'john' (length=9)
1 => 
object(stdClass)[29]
  public 'vgro_name' => string 'GROUP1' (length=4)
  public 'vusr_user' => string 'alice' (length=4)
2 => 
object(stdClass)[30]
  public 'vgro_name' => string 'GROUP2' (length=3)
  public 'vusr_user' => string 'mark' (length=3)

这不是我想要的。我假装的是例如:

 0 => 
object(stdClass)[31]
  public 'vgro_name' => string 'GROUP1' (length=7)
  public 'vusr_user' => string 'john' (length=7)
  public 'vusr_user' => string 'alice' (length=7)

    2 => 
object(stdClass)[30]
  public 'vgro_name' => string 'GROUP2' (length=3)
  public 'vusr_user' => string 'mark' (length=3)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

你可以进行分组'用PHP:

x[:3], x[3:7],x[7:11] ...