dtukyb8095 2015-10-26 17:10
浏览 41
已采纳

如何在PHP中创建子查询?

So I am working on an existing system and I am trying to figure out how they have their mysql setup. They have a query setup like this

    $this->db->select('nID, nAID');
    $this->db->where('bValid', 1);
    $this->db->where('nID', (int)$nID);
    $this->db->from('event');
    $this->db->group_by('nID, nAID');

    $query = $this->db->get();

And this query works great, however I need to setup a sub query. I have written the query in SQL and tested it to confirm that it works but I am having trouble figuring out how to translate it. Basically what I need is rather than grabbing from 'event' table I need to grab from a sub selection I make prior to this. How I imagine it will be.

    $this->db->select('nID, nAID');
    $this->db->where('bValid', 1);
    $this->db->where('nID', (int)$nID);
    $this->db->from(
         $this->db->select('something, somethingelse');
         $this->db->where('something', 1);
         $this->db->get();  
    );
    $this->db->group_by('nID, nAID');

    $query = $this->db->get();
  • 写回答

2条回答 默认 最新

  • doupi6737 2015-10-26 17:43
    关注

    Step 1: Put this code into DB_active_rec.php

     // --------------------------------------------------------------------
        /**
        * Get SELECT query string
        *
        * Compiles a SELECT query string and returns the sql.
        *
        * @param    string    the table name to select from (optional)
        * @param    bool    TRUE: resets QB values; FALSE: leave QB vaules alone
        * @return    string
        */
       public function get_compiled_select($table = '', $reset = TRUE)
       {
           if ($table !== '')
           {
               $this->_track_aliases($table);
               $this->from($table);
           }
    
           $select = $this->_compile_select();
    
           if ($reset === TRUE)
           {
               $this->_reset_select();
           }
    
           return $select;
       }
    

    Step 2: Try this

    //Subquery
    $this->db->select('something, somethingelse');
    $this->db->where('something', 1);
    $this->db->from('first_table');
    $sub_query = $this->db->get_compiled_select();
    
    
    $this->db->select('nID, nAID');
    $this->db->where('bValid', 1);
    $this->db->where('nID', (int)$nID);
    $this->db->from("($sub_query) as tbl1");
    $this->db->group_by('nID, nAID');
    
    $query = $this->db->get();
    

    Tell me if it works.

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

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用