简体   繁体   中英

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

I have two tables.

Table 1: table_company

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

Table 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       |
+-----------------------------------------------------+

I want to join this 2 tables to get the company name according to category_id.

I wrote the following code in my model. but did not get anything. Please help.

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;
}

try to replace your join with this:

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

you can find more examples in codeigniter active record page

Use Left Join for this

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;
}

在此处输入图片说明

First of all open your database error from database.php file only on development line not on production.

Than issue is that company_id is available in both tables with same name than you must need to add table alias as:

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM