Mysql 需要SQL查询通过在codeigniter中连接两个表来获取值
我有两张桌子 表1:Table_公司Mysql 需要SQL查询通过在codeigniter中连接两个表来获取值,mysql,codeigniter,Mysql,Codeigniter,我有两张桌子 表1:Table_公司 +---------------------------+ | company_id | company_name | +---------------------------+ | 1 | Apple | | 2 | Samsung | +---------------------------+ 表2:表2产品 +------------+--------------+-------------
+---------------------------+
| company_id | company_name |
+---------------------------+
| 1 | Apple |
| 2 | Samsung |
+---------------------------+
表2:表2产品
+------------+--------------+-------------+-----------+
| 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获取公司名称
我在我的模型中编写了以下代码。但是什么也没有得到。请帮忙
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');
你可以在中找到更多的例子,使用左连接
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\u 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;
}
这张图片解释了一切选择了最佳答案,并标记为已接受。