需要一个SQL查询来通过在codeigniter中连接两个表来获取值

时间:2016-01-31 16:27:28

标签: mysql 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       |
+-----------------------------------------------------+

我想根据category_id加入这2个表来获取公司名称。

我在我的模型中编写了以下代码。但没有得到任何东西。请帮忙。

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

3 个答案:

答案 0 :(得分:1)

尝试用此替换您的联接:

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

您可以在codeigniter active record page

中找到更多示例

答案 1 :(得分:1)

使用左连接

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

enter image description here

答案 2 :(得分:0)

首先,只在生产线上的开发线上从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; 
}