我已将您的查询转换为像这样更优化
SELECT
id,
ospos_people.first_name,
ospos_people.last_name,
customer_id,
is_draft
from (SELECT
ospos_quotations.id,
ospos_quotations.customer_id,
ospos_quotations.is_draft,
ospos_quotations.date
from ospos_quotations
LEFT JOIN ospos_quotation_items
ON ospos_quotations.id = ospos_quotation_items.quotation_id
where ospos_quotation_items.line = 1) AS T
LEFT OUTER JOIN ospos_people
on T.customer_id = ospos_people.person_id
在这个内部查询中,我使用了 join 而不是 FROM table1, table2
您可以像这样转换查询
为此,您可以使用 codeigniter 的子查询方式来执行此操作,您将不得不破解 codeigniter。像这样。转到 system/database/DB_active_rec.php 从这些函数中删除 public 或 protected 关键字
public function _compile_select($select_override = FALSE)
public function _reset_select()
现在子查询写入可用现在这是您的带有活动记录的查询
function myquery()
{
$select = array(
'ospos_quotations.id',
'ospos_quotations.customer_id',
'ospos_quotations.is_draft',
'ospos_quotations.date'
);
$this->db->select($select);
$this->db->from('ospos_quotations');
$this->db->join('ospos_quotation_items','ospos_quotations.id= ospos_quotation_items.quotation_id ','left');
$this->db->where('ospos_quotation_items.line',1);
$subQuery = $this->db->_compile_select(); // get query string
$this->db->_reset_select(); // reset the object to write new query
unset($select);
$select = array(
'id',
'ospos_people.first_name',
'ospos_people.last_name',
'customer_id,is_draft'
);
$this->db->select($select);
$this->db->from("($subQuery) AS T");
$this->db->join('ospos_people','T.customer_id = ospos_people.person_id ','left outer');
return $this->db->get()->result();
}
事情就完成了。干杯!!!注意:在使用子查询时,您必须使用
$this->db->from('table_name')
代替
$this->db->get('table_name')
运行查询。
编辑:
这是另一种方法。简单使用$this->db->query($query)
函数
function myquery()
{
$query = " SELECT
id,
ospos_people.first_name,
ospos_people.last_name,
customer_id,
is_draft
from (SELECT
ospos_quotations.id,
ospos_quotations.customer_id,
ospos_quotations.is_draft,
ospos_quotations.date
from ospos_quotations
LEFT JOIN ospos_quotation_items
ON ospos_quotations.id = ospos_quotation_items.quotation_id
where ospos_quotation_items.line = 1) AS T
LEFT OUTER JOIN ospos_people
on T.customer_id = ospos_people.person_id";
return $this->db->query($query)->result();
}