如何在CI

时间:2017-07-29 18:54:53

标签: sql codeigniter subquery

大家好我正在尝试在codeigniter中运行子查询。我已经完成了这个

$this->db->where('id NOT IN (SELECT friend_id FROM friend_list WHERE user_id = '$id')');

我的功能看起来像这样

public function get_all_users()
{

    $id=$this->session->userdata['user_id'];
    $this->db->select("id,username");
    $this->db->where('id NOT IN (SELECT `friend_id` FROM `friend_list` WHERE `user_id` = '$id')');
    $this->db->where('id !=2');
    $this->db->from('users');
    $query=$this->db->get();

    if ($query->num_rows() > 0)
    {
       return $query->result();
    }

    return false;
}

但它正在返回此错误

    Message: syntax error, unexpected '$id' (T_VARIABLE), expecting ',' or ')'.

如果我在$ id的步伐中加上一些值,那么它会给出结果。我怎么能解决这个问题。请帮帮我。

2 个答案:

答案 0 :(得分:1)

首先,您需要包含子查询库:

$this->load->library('subquery');

然后把你的查询这样:

这就是我们如何在CI中编写子查询 方法1:

$this->db->where('id NOT IN (SELECT `friend_id` FROM `friend_list` WHERE `user_id` = '$id')', NULL, FALSE);

或者您也可以这样写: 方法2:

$this->db->select('id,username')->from('users');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('friend_id')->from('friend_list');
$sub->where('user_id', $id);
$this->subquery->end_subquery('id', FALSE);

你可以查看这个参考: subquery in codeigniter active record

答案 1 :(得分:1)

你忘了逃避同一个(单个)引用:

你应该把它写成:

$this->db->where('id NOT IN (SELECT `friend_id` FROM `friend_list` WHERE `user_id` = \'$id\')');

$this->db->where('id NOT IN (SELECT `friend_id` FROM `friend_list` WHERE `user_id` = ' . $id . ')');

$this->db->where("id NOT IN (SELECT `friend_id` FROM `friend_list` WHERE `user_id` = '$id')");