所以我在一个现有的系统上工作,我试图弄清楚他们如何进行mysql设置。他们有这样的查询设置

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


而且此查询的效果很好,但是我需要设置一个子查询。我已经用SQL编写了查询并对其进行了测试,以确认它是否有效,但是我在弄清楚如何翻译时遇到了麻烦。基本上,我需要的不是从“事件”表中获取,我需要从在此之前所做的子选择中获取。我想像会怎样。

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

最佳答案

步骤1:将此代码放入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;
   }


步骤2:尝试一下

//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();


告诉我是否可行。

10-06 07:28
查看更多