dqk77945 2010-11-17 22:31
浏览 57
已采纳

MySQL选择(Zend Framework DB Select)

I have the following select:

public function fetchFooSum($id)
    {
        $db = Zend_Registry::get('dbAdapter');
        $select = $db->query("SELECT SUM(prod) FROM `output` WHERE loc_id IN (SELECT loc_id FROM `locations` WHERE location_id = ".$id.");");

        return $select->fetchAll();
    }

I have 2 questions about this:

  1. Is this considered a reasonably acceptable way to form such a query?

        SELECT SUM(prod) FROM output WHERE loc_id IN (SELECT loc_id FROM locations WHERE location_id = ".$id.");
    

    or is that not ideal (should I be using some other way of doing this... a join or union or somesuch thing that I've heard of but am not clear on when to use)...

  2. Within the Zend Framework, how would you formulate such a query?

The method I am using works but I doubt it is the ideal way to do it (both as a regular SQL query and in the way I do it within Zend Framework).

Any advice about the query or how to better implement it in ZF is appreciated.

  • 写回答

2条回答 默认 最新

  • duankuan5319 2010-11-17 22:55
    关注

    I would prefer an inner join to using the IN operator for this query as I believe it will outperform your query in its current form (but do not yet have a reference as to why :)

    // example using Zend_Db_Select
    $select = $db->select()
                 ->from('output', array('sum(prod)'))
                 ->join('locations', 'output.loc_id = locations.loc_id', array())
                 ->where('locations.location_id = ?', $id);
    
    // to dump query
    print_r($select->__toString());
    
    // to execute
    $result = $db->fetchOne($select);
    

    I would strongly recommend reading the Zend_Db_Select documentation which has plenty of practical examples - and shouldn't take more than an hour.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?