![](/img/trans.png)
[英]How to remove redundant data in table from SQL query with join in codeigniter
[英]SQL Query Join in CodeIgniter
我有這個查詢,我需要它采用 CodeIgniter 方式(查詢生成器)。 我知道如何使用標准 查詢生成器 class函數,但我很難找到一種方法, SELECT
使用 CI 查詢生成器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 的困難在於左連接內的 select 部分。 您可以使用join() function 將 $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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.