我在db中有这个表:
user
-id
-name
-role_id (related to a role-table)
示例数据:
name of user1. id=1, role_id = 2, old_userid = 0
name of user2. id=2, role_id = 2, old_userid = 0
name of user3. id=3, role_id = 2, old_userid = 0
name of user4, id=4, role_id = 3, old_userid = 2
name of user5, id=5, role_id = 3, old_userid = 2
name of user6, id=6, role_id = 3, old_userid = 4
我可以通过以下方式获取此旧用户列表:
$this->db->select('u.name')->from('user u');
$this->db->where('u.old_userid >', '0');
它将返回
name of user4
name of user5
name of user6
但我想:
name of user2[user4, user5] //user4 and user5 has older_userid as 2
name of user6[user4] //user6 has older_userid as 4
role_id=3
与旧用户相同(具有role_id的用户始终具有old_userid> 0)。
我有点被困在这里。思考如下:
$this->db->select('u.id, u.name, GROUP_CONCAT(old_userid) AS uid')->from('user u');
$this->db->group_by('u.old_userid');
帮助请某人......: - )
即使在纯粹的SQL中我也很感激。
答案 0 :(得分:1)
你可以这样做
$this->db
->select('o.name, GROUP_CONCAT(u.name) AS `old_users`' ,FALSE)
->from('user u')
->join('user o','u.old_userid=o.id','LEFT')
->where('u.role_id',3)
->group_by('u.old_userid')
->get()
;
请注意,您需要在选择的第二个参数中显示FALSE,以免受额外的反向标记