我有这个 SQL 查询,在正常的 sql 语法中是这样的
SELECT *
FROM question
LEFT JOIN abcd_selection ON question.questionID = abcd_selection.questionID
WHERE question.SurveyID =21
这很好用,我得到了我想要的。然而,当我将它切换到 CI 时,它并没有奇怪地工作。对于与 abcd_selection 不匹配的行,questionID 列会消失。
$this->db->select('*');
$this->db->from('question');
$this->db->join('abcd_selection','question.QuestionID = abcd_selection.QuestionID', 'left');
$this->db->where('question.SurveyID', $input_qid);
$query = $this->db->get();
谁能解决这个问题??
最佳答案
当连接 2 个具有相同列名的表时,如果第二个表中没有匹配的行,您将得到一个 NULL
值。
question.SurveyID question.QuestionID abcd_selection.QuestionID
1 2 2 //matching row in abcd_selection
2 3 NULL //no matching row in abcd_selection
由于列名相同,php 将选择 QuestionID
的最后一个实例,当匹配行不存在时,它将为 NULL
。
解决这个问题的一种方法是选择该列作为别名
$this->db->select('*,question.QuestionID as QID');
现在即使 abcd_selection.QuestionID
不存在,您也可以选择 $query['QID']
。
关于php - CodeIgniter SQL 查询缺少列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954022/