2

我想Mysql Concat Functionlike expression.
我想合并firstnamelastnameasfullname并根据fullname.
我在 YII1 中试过这个。下面是我的代码:

    $criteria = new CDbCriteria();
    $criteria->select = "*";
    $criteria->select = 'CONCAT(firstname , "" ,  lastname) AS fullname';
    $criteria->addCondition('fullname LIKE :match');
    $criteria->params = array(':match' => $query);
    $models = User::model()->findAll($criteria);

以下是生成的错误消息:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fullname' in 'where clause'
(Error 500)
    CDbCommand::fetchColumn() failed: SQLSTATE[42S22]: Column not found: 1054
Unknown column 'fullname' in 'where clause'. The SQL statement executed
was: SELECT COUNT(*) FROM `members` `t` WHERE fullname LIKE :match.

提前致谢

4

2 回答 2

2

If you don't need the fullname afterwards, you can just use the CONCAT method in the WHERE clause:

$criteria = new CDbCriteria();
$criteria->addCondition('CONCAT(userId , " " , username) LIKE :match');
$criteria->params = array(':match' => $query);
$models = User::model()->findAll($criteria);

However, if you do want to keep the fullname in the SELECT clause, you can only use this alias in the HAVING clause:

$criteria = new CDbCriteria();
$criteria->select = '*, CONCAT(userId , " " , username) AS fullname';
$criteria->having = 'fullname LIKE :match';
$criteria->params = array(':match' => $query);
$models = User::model()->findAll($criteria);

Please note that your User model should have a fullname attribute in this case, otherwise you won't be able to access the fullname field.

于 2014-11-11T22:49:45.283 回答
0

我认为这是一种更面向 OO 的使用方式SQL Functions(顺便说一句,@JonathanStevens 的回答是正确的):

$criteria = new CDbCriteria();    
    $criteria->select = ['*', new \CDbExpression("CONCAT(firstName, ' ', lastName) as fullname")];
    $criteria->addCondition('CONCAT(firstName, ' ', lastName) LIKE :match'); <<<< This is still a problem
    $criteria->params = array(':match' => $query); 
    $models = User::model()->findAll($criteria);

更新

如果您使用Mysql的问题是在 where 子句中使用此聚合列(全名)。
如果您只是选择该列(全名)并通过模型中的人工属性获取它,那没关系,但如果您想在where clause查询中使用它,这是不可能的,因为它受 MYSQL 服务器的限制。这是您将得到的错误:

#1054 - Unknown column 'fullname' in 'where clause'

所以你也需要在 where 子句中重复你的 SQL 函数(concat)(你不能在 where 子句中使用别名列)。

于 2016-01-26T09:31:25.407 回答