【问题标题】:Zend_Db_Select EXISTSZend_Db_Select 存在
【发布时间】:2011-11-16 09:02:28
【问题描述】:

我的查询的一部分是 EXISTS 条件:

$select->where(
  'EXISTS(' .
  'SELECT `price_property_id` FROM `property_price` ' .
    'WHERE `price_property_id` = `pu_property_id`' .
      ' AND `price_value` >= ' . $params['price_min'] .
      ' AND `price_value` <= ' . $params['price_max'] .
   ')'
);

它如何在 Zend Framework 中以正确的方式编写?

【问题讨论】:

    标签: zend-framework zend-db-select


    【解决方案1】:

    我创建子查询和子选择作为新的 Zend_Db_Select 对象。这使代码更简洁,因为我可以在其他地方重用该查询,它还有助于调试,因为我可以echo (string)$subQuery 来查看 SQL 的那部分。

    $subQuery = new Zend_Db_Select();
    $subQuery->from(array('price' => 'property_price'))
         ->where('price_property_id = pu_property_id')
         ->where('price_value >= ?', $params['price_min'])
         ->where('price_value <= ?', $params['price_max']);
    
    $select->where('EXISTS('.$subQuery.')');
    

    【讨论】:

    • $select-&gt;where('EXISTS('.$subQuery.')'); 失败,因为 $subQuery 不是字符串(至少在 ZF2 中)
    【解决方案2】:

    我相信这就是你要找的东西!:

    <?php
    
    // $select is instance of Zend_Db_Select
    // $db is instance of Zend_Db_Adapter
    
    $select->where('exists (?)', new Zend_Db_Expr(
        $db->quoteInto('select * from your_table where id = ?', $id, Zend_Db::PARAM_INT)
    ));
    
    ?>
    

    【讨论】:

      【解决方案3】:

      据我所知,Zend_Db_Select 没有特定方法可以在where 子句中包含子查询。我认为您无法进一步改进它,它的编写方式。

      您可以将子查询重写为OUTER JOIN,并且可以利用更多Zend_Db_Select 方法,但我不确定这样做的好处,只要您的代码正常工作并且清晰易读。

      希望对你有帮助,

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        • 2014-10-12
        • 2011-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多