CodeIgniter中的SQL查询联接



我有这个查询,我需要它以CodeIgniter的方式(查询生成器(。我知道如何使用标准的查询生成器类函数,但我很难找到如何使用CI查询生成器类构建具有内部SELECT子句的LEFT JOIN的方法。

SELECT * 
FROM   sma_products p 
LEFT JOIN (SELECT product_id, 
Count(*) 
FROM   sma_sale_items 
GROUP  BY product_id) s 
ON p.id = s.product_id 
ORDER  BY ` Count(*) ` DESC 

使用CI查询生成器创建此SQL的困难在于左联接中的选择部分。您可以使用join((函数将$table参数替换为SELECT部分:来构建它

join($table,$cond[,$type=''[,$escape=NULL]](参数:

$table (string) – Table name to join
$cond (string) – The JOIN ON condition
$type (string) – The JOIN type
$escape (bool) – Whether to escape values and identifiers

这是最后一个CI代码:

$q=$this->db1   ->select ('*')
->join('(
select `product_id`
,count(*) 
from `sma_sale_items`
group by `product_id`
) s','p.id = s.product_id','left')
->order_by('count(*)', 'DESC')
->get('sma_products p');
return $q->result();

最新更新