簡體   English   中英

需要一個SQL查詢以通過在Codeigniter中聯接兩個表來獲取值

[英]Need a SQL query to get a value by joining two table in codeigniter

我有兩張桌子。

表1:table_company

+---------------------------+
| company_id | company_name |
+---------------------------+
| 1          | Apple        |
| 2          | Samsung      |
+---------------------------+

表2:table_products

+------------+--------------+-------------+-----------+
| product_id | product_name | category_id |company_id |
+-----------------------------------------------------+
| 1          | iPhone       |      3      |   1       |
| 2          | galaxy       |      3      |   2       |
| 1          | iPad         |      4      |   1       |
| 2          | tab          |      4      |   2       |
+-----------------------------------------------------+

我想加入這2個表以根據category_id獲得公司名稱。

我在模型中編寫了以下代碼。 但什么也沒得到。 請幫忙。

public function select_company_by_category_id($category_id) {
    $this->db->select('*');
    $this->db->from('tbl_products');
    $this->db->join('tbl_company', 'company_id = company_id');
    $this->db->where('category_id', $category_id);
    $query_result = $this->db->get();
    $result = $query_result->result();
    return $result;
}

嘗試以此替換您的聯接:

$this->db->join('tbl_company', 'tbl_company.company_id = tbl_products.company_id');

您可以在codeigniter活動記錄頁面中找到更多示例

為此使用左聯接

public function select_company_by_category_id($category_id) {
    $this->db->select('*');
    $this->db->from('table_products');
    $this->db->join('table_company', 'table_company.company_id = table_products.company_id', 'left'); # Changed 
    $this->db->where('table_products.category_id', $category_id); # Changed 
    $query = $this->db->get(); # Improved 
    $result = $query->result_array(); # Improved 
    return $result;
}

在此處輸入圖片說明

首先,僅在開發生產線上而不是生產線上從database.php文件打開數據庫錯誤。

問題在於,兩個表中都可以使用company_id ,且名稱相同,而不需要添加表別名,例如:

public function select_company_by_category_id($category_id) 
{ 
    $this->db->select(); 
    $this->db->from('table_products'); 
    $this->db->join('table_company', 'table_company.company_id = table_products.company_id'); 
    $this->db->where('table_products.category_id',  $category_id); 
    $query = $this->db->get(); 
    $result = $query->result_array(); 
    return $result; 
}

暫無
暫無

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

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