我在使用Criteria params和table别名时遇到问题。我需要得到这个查询:
SELECT x.* FROM stl_election x
JOIN (SELECT agent_id, economy_id, MAX(outcome) max_outcome FROM stl_election WHERE economy_id = 92 AND agent_id = 6203 GROUP BY stl_election.economy_id) y
ON y.max_outcome-3 <= x.outcome
AND y.economy_id = x.economy_id
AND y.agent_id = x.agent_id
我已经做到了:
$election = StlElection::model();
$criteria = new CDbCriteria;
$criteria->select = "agent_id, economy_id, MAX(outcome) max_outcome";
$criteria->condition = 'agent_id=:agent_id AND economy_id=:economy_id';
$criteria->params = array(
':agent_id' => $agent->id,
':economy_id' => $this->economy->id
);
$criteria->group = 'stl_election.economy_id';
$bestChoiceSql = $election->getCommandBuilder()->createFindCommand($election->getTableSchema(), $criteria)->getText();
$criteria2 = new CDbCriteria;
$criteria2->join = '(' . $bestChoiceSql . ') y ON y.max_outcome-3 <= x.outcome
AND y.economy_id = x.economy_id
AND y.agent_id = x.agent_id';
$criteria2->alias = 'x';
$considerChoices = StlElection::model()->findAll($criteria2);
输出结果为:
Invalid parameter number: no parameters were bound. The SQL statement executed was: SELECT `t`.`agent_id`, `t`.`party_id`, `t`.`economy_id`, `t`.`outcome` FROM `stl_election` `t` (SELECT agent_id, economy_id, MAX(outcome) max_outcome FROM `stl_election` `t` WHERE agent_id=:agent_id AND economy_id=:economy_id GROUP BY stl_election.economy_id) y ON y.max_outcome-3 <= x.outcome
AND y.economy_id = x.economy_id
AND y.agent_id = x.agent_id
答案 0 :(得分:0)
在我看来,你是从SQL的角度来看这个,而不是Yii的观点。我建议你学习模型关系和CDbCriteria的功能。
注意,对于CDbCriteria,如果您打算使用 - &gt; with()函数,那么一定要包括 - &gt; together = true;
Yii CDbCriteria Class Reference
您的简单答案可能只是执行SQL查询,请尝试:
$query = "SELECT x.* FROM stl_election x
JOIN (SELECT agent_id, economy_id, MAX(outcome) max_outcome FROM stl_election WHERE economy_id = 92 AND agent_id = 6203 GROUP BY stl_election.economy_id) y
ON y.max_outcome-3 <= x.outcome
AND y.economy_id = x.economy_id
AND y.agent_id = x.agent_id";
$result = Yii::app()->db->createCommand($sql)->queryAll();
答案 1 :(得分:0)
如果有人有兴趣回答:
$election = StlElection::model();
$criteria = new CDbCriteria;
$criteria->select = "agent_id, economy_id, MAX(outcome) max_outcome";
$criteria->condition = 'agent_id=:agent_id AND economy_id=:economy_id';
$criteria->params = array(
':agent_id' => $agent->id,
':economy_id' => $this->economy->id
);
$criteria->group = 'stl_election.economy_id';
$bestChoiceSql = $election->getCommandBuilder()->createFindCommand($election->getTableSchema(), $criteria)->getText();
$criteria2 = new CDbCriteria;
$criteria2->join = 'JOIN (' . $bestChoiceSql . ') y ON y.max_outcome-3 <= x.outcome
AND y.economy_id = x.economy_id
AND y.agent_id = x.agent_id';
$criteria2->alias = 'x';
$considerChoices = StlElection::model()->findAll($criteria2);
我错过了'加入' - &gt;加入:/