【问题标题】:Order clause with 'like' clause in Zend DBZend DB 中带有“like”子句的 Order 子句
【发布时间】:2011-08-19 06:44:56
【问题描述】:

查询:

select * from table_name ORDER BY name like 'C%' DESC;

此查询在 MySql 中运行良好,但我无法使用 Zend DB 构建查询。 执行时出错。

PHP 数据库代码:

$result = $this->getDefaultAdapter() ->select() ->from($this->_name,array('*')) ->order("name like 'C%' DESC") ->query() ->fetchAll();

错误:

未找到列:1054 未知列 'name like 'C%'' in 'order Clause'

提前致谢

【问题讨论】:

    标签: php zend-framework mysql-error-1054


    【解决方案1】:

    Zend_Db_Select 尝试将字符串分隔为列名,但如果您传递 Zend_Db_Expr 类型的对象而不是字符串,它会跳过此操作:

    ->order(new Zend_Db_Expr("name like 'C%' DESC"))->
    

    还有一个未记录的快捷方式:列分隔函数假定任何包含括号的字符串很可能是一个表达式,而不仅仅是一个列名。所以以下方法也可以:

    ->order( "(name like 'C%' DESC)" )->
    

    【讨论】:

      【解决方案2】:

      我不熟悉zend,但尝试像这样在Zend中重写你的sql查询

      select *, (`name` like 'C%') as theFiled from  table_name by theFiled desc;
      

      虽然我不太确定我猜 Zend Code 一定是这样的,

       $result = $this->getDefaultAdapter() ->select() 
      ->from($this->_name,array('*', "theFiled" => "name like 'C%'") ->order("theFiled DESC") 
      ->query() ->fetchAll();
      

      【讨论】:

      • 这也可以,但您还必须将 LIKE 表达式设为 Zend_Db_Expr,否则将其放在括号中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多