(Yii)CDbCommand无法执行SQL语句:SQLSTATE [42000]:语法错误或访问冲突:

时间:2014-10-15 05:54:44

标签: php mysql sql yii

我正在尝试执行此sql查询但发生异常...我在PhpMyAdmin中尝试了查询并且它运行正常。

<?php
        $criteria=new CDbCriteria;
        $criteria->condition='select min(purchase_order_id) from purchase_order where purchase_order_id >'.$model->purchase_order_id;
        $nextfield = \POrder::model()->model()->findAll($criteria);
           ?>

例外是, CDbCommand无法执行SQL语句:SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法中有错误;查看与您的MySQL服务器版本相对应的手册,以便在第1行的purchase_order(purchase_order_id&gt; 65')的'select min(purchase_order_id)附近使用正确的语法。执行的SQL语句是:SELECT * FROM purchase_order { {1}} WHERE从purchase_order选择min(purchase_order_id),其中purchase_order_id> 65

1 个答案:

答案 0 :(得分:1)

如果您只想查询结果,请执行以下操作:

Yii::app()->db->createCommand("
SELECT MIN(purchase_order_id) FROM purchase_order
WHERE purchase_order_id > :purchase_order_id
")->queryScalar(array('purchase_order_id'=>$model->purchase_order_id'));

这将返回从phpmyadmin或mysql workbench获得的单个值。

如果您想要与该purchase_order_id对应的模型记录,则可以执行以下操作:

$criteria=new CDbCriteria;
$criteria->addCondition("t.purchase_order_id = (
SELECT MIN(purchase_order_id)
FROM purchase_order
WHERE purchase_order_id > :previous_purchase_order_id)");
$criteria->params['previous_purchase_order_id'] = $model->purchase_order_id;
$nextfield = \POrder::model()->model()->find($criteria);

我假设只有一个这样的模型,所以我将findAll更改为find