Php CodeIgniter内部连接第三个表
我在添加第三个表时遇到了一点小麻烦 这是表结构:Php CodeIgniter内部连接第三个表,php,codeigniter,Php,Codeigniter,我在添加第三个表时遇到了一点小麻烦 这是表结构: products = id name code 5 product1 002 522 product1 002 warehouses = id code name address city 1 store1 store1 store1 store1 warehouses_products = id product_id warehouse_id quantity
products =
id name code
5 product1 002
522 product1 002
warehouses =
id code name address city
1 store1 store1 store1 store1
warehouses_products =
id product_id warehouse_id quantity
2 5 1 -3
3 522 1 -2
4 446 1 0
以下是获取数据的函数:
$this->load->library('tables');
$this->tables
->select("products.id as productid, name, code (CASE WHEN sum(warehouses_products.quantity) Is Null THEN 0 ELSE sum(warehouses_products.quantity) END) as totalQuantity, warehouses.name");
$this->tables->from('products');
$this->tables->join('warehouses_products', 'products.id=warehouses_products.product_id', 'left');
$this->tables->join('warehouses', 'warehouses_products.id=warehouses.warehouse_id', 'left');
$this->tables->group_by("products.id");
$this->tables->unset_column('productid');
echo $this->tables->generate();
非常感谢您的帮助您的加入查询看起来很好。。只是我注意到(如果不是worng)您有一个
,
而不是
在select查询中。。
试试这个
替换此
$this->tables->select("table1.id as table1id, column1, column2, table2.column1, table3,column2")
与
还要确保(检查)您正在运行的查询是否正确。。您可以通过打印CI中最后运行的查询来完成此操作
echo $this->db->last_query();exit; //after query is made ..
还有你最新的问题。。联接不正确
已更新
这个
取代
$this->tables->join('table3', 'table3.product_id=table1.id', 'left'); //join the thrid table first
$this->tables->join('table2', 'table2.id=table3.warehouse_id', 'left');//and thn the second table with third tables warehouse_id
您能显示错误消息吗?没有错误,我无法在datatable中加载数据。结果为空。
table1.column\u id
是否在table1
中?因为我看到您在选择中使用表1.id
,所以第1列和第2列在表1中,我的意思是列id
。或者您可以粘贴表的结构吗?我已经更新了查询并添加了表结构,以便更好地理解。您好,我有echo$this->tables->generate();如果我添加echo$this->db->last_query();出口仍在处理中,从服务器加载数据,因为存在服务器端请求。是的,您可以检查firefox firebug Inner net panel中的最后一个查询…如果我根据您更新的问题更新了我的答案,请也尝试一下..结果是SELECT*from(设置
)?你试过我答案中更新的部分了吗。。。我认为这应该行得通
$this->tables->join('table2', 'table3.product_id=table1.id', 'left');
$this->tables->join('table3', 'table2.id=table3.warehouse_id', 'left');
$this->tables->join('table3', 'table3.product_id=table1.id', 'left'); //join the thrid table first
$this->tables->join('table2', 'table2.id=table3.warehouse_id', 'left');//and thn the second table with third tables warehouse_id