简体   繁体   English

sql命令无法正确执行

[英]sql command does not execute properly

I have a two tables in my database instructors and courses . 我的数据库instructorscourses有两个表格。 I want to join them and for this reason wrote this code 我想加入他们,因此写了这段代码

$this->db->join('instructors', 'instructors.id = courses.instructor_id', 'left');
$query = $this->db->get_where('courses', array('courses_slug' => $slug));
return $query->row_array();

This code means: 该代码表示​​:

SELECT * FROM `courses` LEFT JOIN `instructors` ON `instructors`.`id` = `courses`.`instructor_id` WHERE `courses_slug` = 'abituriyent-hazirligi'

But when I write this code to check: 但是当我编写此代码进行检查时:

$data['courses'] = $this->popular_courses_model->get_popular_courses($slug);
echo $data['courses']['id'];
die();

It writes the instructors id, not id of the course. 它写的是教师的ID,而不是课程的ID。 Where can be the problem? 问题出在哪里? Thanks in advance. 提前致谢。

You are joining two table with columns of the same name ('id'). 您正在将两个具有相同名称('id')列的表联接在一起。 You need to be specific in your select for the columns and rename ('AS') if necessary. 您需要在选择列时具体说明,并在必要时重命名('AS')。

select courses.id as course_id, instructor.id as instructor_id, ...

When using joins you should explicitly call out what columns you want returned like: 使用联接时,您应该明确指出要返回的列,例如:

$select = "c.id, c.name, c.instructor_id, i.name instructor_name";

return $this->db->select($select)
//equivalent to "instructors as i" 
->join('instructors i', 'i.id = c.instructor_id', 'left')
->where('c.courses_slug', $slug)
//equivalent to "courses as c" 
->get('courses c')->row_array();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM