簡體   English   中英

限制 SQL 加入時使用 CodeIgniter 活動記錄 class

[英]Limit SQL join when using CodeIgniter active record class

我正在獲取產品列表。 每個產品可能有一張或多張圖片,我只想返回第一張圖片。

$this->db->select('p.product_id, p.product_name i.img_name, i.img_ext');    
$this->db->join('products_images i', 'i.product_id = p.product_id', 'left');
$query = $this->db->get('products p');

無論如何使用CI活動記錄class將db->join限制為1條記錄?

添加$this->db->limit(1); 在調用$this->db->get('products p'); . 請參閱ellislab.com上的文檔:在頁面中搜索limit

編輯:我誤讀了您試圖將 LIMIT 應用於內部 JOIN 語句的事實。

不,由於您不能在常規 SQL 中對內部 JOIN 語句執行 LIMIT,因此您不能使用 Code Igniter 的 ActiveRecord ZA2F2ED4F8EBC2CBB4C21A29DC40AB61Z 來執行此操作。

您可以使用帶有left連接的$this->db->group_by來實現您想要的:

$this->db->select('products.id, products.product_name, products_images.img_name, products_images.img_ext');
$this->db->from('products');
$this->db->join('products_images', 'products_images.product_id = products.id', 'left');
$this->db->group_by('products.id'); 
$query = $this->db->get();

這應該通過products.id為您提供結果(不重復產品),並將products_images中的第一個匹配記錄連接到每個結果行。 如果連接表中沒有匹配的行(即如果缺少圖像),您將獲得 products_images 字段的 null 值,但仍會從products表中看到結果。

擴展@Femi的答案:

沒有限制JOIN的好方法,事實上,你也不想這樣做。 假設products_image.product_idproducts.id都有索引(如果你要反復加入它們,它們絕對應該)當數據庫引擎進行連接時,它使用索引來確定它需要獲取哪些行。 然后引擎使用結果來確定在磁盤上的哪個位置找到它需要的記錄。 如果你

通過運行這些 SQL 語句,您應該能夠看到差異:

EXPLAIN 
SELECT p.product_id, p.product_name, i.img_name, i.img_ext
FROM products p
LEFT JOIN products_images i
    ON i.product_id = p.product_id

相對於:

EXPLAIN  
SELECT p.product_id, p.product_name, i.img_name, i.img_ext
FROM (SELECT product_id, product_name FROM products) p 
LEFT JOIN (SELECT img_name, img_ext FROM products_images) i
    ON i.product_id = p.product_id

第一個查詢應該有一個索引,第二個沒有。 如果數據庫中有大量行,則應該存在性能差異。

如果 product_id 存在於前一個中,那么我解決的方法也是迭代結果並刪除當前的 object。 創建一個數組,將 product_id 推送給它,同時檢查它們是否重復。

$product_array = array();
$i = 0;

foreach($result as $r){

    if(in_array($r->product_id,$product_array)){
        unset($result[$i]);
    }else{
        array_push($product_array,$r->product_id);
    }
    $i++;

} 

$result = array_values($result); //re-index result array

現在 $result 就是我們想要的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM