[英]Need a SQL query to get a value by joining two table in codeigniter
I have two tables. 我有两张桌子。
Table 1: table_company 表1:table_company
+---------------------------+
| company_id | company_name |
+---------------------------+
| 1 | Apple |
| 2 | Samsung |
+---------------------------+
Table 2: table_products 表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. 我想加入这2个表以根据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 您可以在codeigniter活动记录页面中找到更多示例
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. 首先,仅在开发生产线上而不是生产线上从database.php文件打开数据库错误。
Than issue is that company_id
is available in both tables with same name than you must need to add table alias as: 问题在于,两个表中都可以使用
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.