如何加入两个表?

时间:2016-01-25 02:48:25

标签: sql codeigniter

Feedback

User

此查询有效。在反馈表中获取数据:

    public function feedback_data()
    {
        $recipe_id = 0;
        $this->db->where('recipe_id',$recipe_id);
        $query = $this->db->get('feedback');
        return $query->result_array();
    }

我需要从反馈表和用户表中的firstname和lastname获取feedback_id和注释,其中来自反馈的user_id等于来自用户的user_id。顺便说一句,这是我的查询,我认为它不起作用。

$this->db->select('f.feedback_id, f.comment, f.recipe_id, f.user_id as Fid'.'u.firstname, u.lastname, u.user_id as Uid');
    $this->db->from('feedback f')
    $this->db->join('user u','u.user_id = f.user_id');
    $this->db->where('f.recipe_id', $recipe_id);
    $query = $this->db->get()->result();
    return $query;

1 个答案:

答案 0 :(得分:0)

请试试这个:

$this->db->select('f.feedback_id, f.comment, f.recipe_id, f.user_id as Fid'.'u.firstname, u.lastname, u.user_id as Uid');
$this->db->from('feedback f')
$this->db->join('user u','u.user_id = f.user_id', 'left');
$this->db->where('f.recipe_id', $recipe_id);
$query = $this->db->get()->result();
return $query;

如果以上代码不起作用,请尝试此操作:

    $this->db->select('f.feedback_id, f.comment, f.recipe_id, f.user_id as Fid'.'u.firstname, u.lastname, u.user_id as Uid');
    $this->db->from('feedback f');
    $this->db->join('user u','u.user_id = f.user_id', 'left');
    $this->db->where('f.recipe_id', $recipe_id);

    $query = $this->db->get();
    if ($query->num_rows() > 0)
    {
        return $query->row_array();
    }