【问题标题】:Yii1: How to use concat function in mysq like queryYii1:如何在类似查询的mysql中使用concat函数
【发布时间】:2014-11-11 14:16:46
【问题描述】:

我想在like expression 中使用Mysql Concat Function
我想将firstnamelastname 合并为fullname 并根据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.

提前致谢

【问题讨论】:

  • 我不是 Yii 专家,但您需要在条件本身中添加 CONCAT(firstname , "" , lastname),因为别名不能用于 where。
  • $criteria = new CDbCriteria(); $标准->选择='*'; $criteria->addCondition('CONCAT(firstname, lastname) AS fullname LIKE :match');但问题仍然存在
  • 没有$criteria->addCondition('CONCAT(firstname , "" , lastname) LIKE :match');

标签: php mysql activerecord yii yii1.x


【解决方案1】:

如果你以后不需要全名,你可以在 WHERE 子句中使用 CONCAT 方法:

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

但是,如果您确实想在 SELECT 子句中保留全名,则只能在 HAVING 子句中使用此别名:

$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);

请注意,在这种情况下,您的 User 模型应该具有 fullname 属性,否则您将无法访问 fullname 字段。

【讨论】:

  • 是的,我已经为模型用户添加了公共 $fullname 属性,它现在正在工作
【解决方案2】:

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

$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 子句中使用别名列)。

【讨论】:

  • 确实如此,但如果将条件移至having 子句,则可以使用别名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 2011-09-01
  • 2018-10-10
  • 2011-05-29
  • 1970-01-01
  • 2011-12-18
相关资源
最近更新 更多