我有2个表用户和user_request
用户
id name
1 U1
2 U2
3 U3
4 U4
5 U5
user_request
id userid name status
1 1 U1 rejected
2 3 U3 rejected
我需要来自用户表的用户列表,但那些用户不应该出现在user_request表中
因此,根据以上示例,我需要以下用户列表
U2
U4
U5
从用户表中我使用以下代码来获取结果
$query = $this->db->get('user');
return $query->result();
我在user_request表中使用以下代码来获取结果
$this->db->where('status','rejected');
$query = $this->db->get('user_request');
return $query->result();
有人可以帮助我获得理想的结果吗?
答案 0 :(得分:1)
从第一个表中获取id,从第二个表中获取userid。从2个数组中删除常用值,您将获得所需的结果
$this->db->select('id');
$query = $this->db->get('user');
$first = $query->result();
foreach ($first as $key)
{
$user_one = $key->id;
$first_array[] = $user_one;
}
$this->db->where('status','rejected');
$query_two = $this->db->get('user_request');
$two = $query_two->result();
foreach ($two as $value)
{
$userid_two = $value->userid;
$second_array[] = $userid_two;
}
$arr_1 = array_diff($first_array, $second_array);
$std = array();
foreach ($arr_1 as $value)
{
$this->db->where('id',$value);
$main_query = $this->db->get('user');
$main = $main_query->result();
$std = array_merge($std,$main);
}
return $std;
答案 1 :(得分:0)
使用NOT IN
:
SELECT name FROM user WHERE id NOT IN (SELECT userid FROM user_request)
更新:对于Codeigniter:
$this->db->select('*')->from('user');
$this->db->where('`id` NOT IN (SELECT `userid` FROM `user_request`)', NULL, FALSE);
答案 2 :(得分:0)
您可以加入:
$this->db->select('name');
$this->db->from('user');
$this->db->join('user_request', 'user.id = user_request.userid');
$this->db->where('status !=','rejected');
return $this->db->get();