如何比较where子句中两个表的列值

时间:2016-12-18 00:40:36

标签: yii2

以下是我尝试使用的方案

game_studentanswer
--> studentanswerid (primary)
--> questionid
--> answerid (this is the answer selected by user)

game_question
--> questionid

game_officialanswer
--> officalanswerid (primary)
--> questionid
--> answerid (this is the answerid for correct answer)

我正在尝试在Yii2中创建此查询:

SELECT COUNT(*) FROM `game_studentanswer` LEFT JOIN `game_question` ON `game_studentanswer`.`questionid` = `game_question`.`questionid` LEFT JOIN `game_officialanswer` ON `game_question`.`questionid` = `game_officialanswer`.`questionid` WHERE (`userid`='1') AND (`game_studentanswer`.`answerid` <> `game_officialanswer`.`answerid`)

这是代码

$query = MyGameStudentanswer::find()->joinWith('question.gameOfficialanswers')
        ->where(['userid'=>$userid])->andWhere(['answerid' => 'question.gameOfficialanswers.answerid']);

我的问题是代码的“AndWhere()”部分 - 而不是比较两列 - 它假设'question.gameOfficialanswers.answerid'为字符串值,因此Yii2执行的查询是

SELECT COUNT(*) FROM `game_studentanswer` LEFT JOIN `game_question` ON `game_studentanswer`.`questionid` = `game_question`.`questionid` LEFT JOIN `game_officialanswer` ON `game_question`.`questionid` = `game_officialanswer`.`questionid` WHERE (`userid`='1') AND (`game_studentanswer`.`answerid` = 'game_officialanswer.answerid') 

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

能够通过在表名和列名周围使用`引号来找到变通方法。

$query = MyGameStudentanswer::find()->joinWith('question.gameOfficialanswers')//->onCondition(['answerid' => 'question.gameOfficialanswers.answerid'])
->where(['userid'=>$userid])->andWhere('`game_studentanswer`.`answerid` = `game_officialanswer`.`answerid`');//->onCondition('questionid=game_officalanswer.questionid');