-1

我在尝试添加第三张桌子时遇到了一些小麻烦。

这是表结构:

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();

任何帮助表示赞赏

4

1 回答 1

1

您的联接查询看起来不错..只是我注意到(如果没有磨损)您 的选择查询中有一个,而不是..试试这个.

换这个。。

$this->tables->select("table1.id as table1id, column1, column2, table2.column1, table3,column2")

$this->tables->select("table1.id as table1id, column1, column2, table2.column1, table3.column2") //notice the '.' here table3.column2

并确保(检查)您正在运行的查询是否正确..您可以通过在 CI 中打印最后运行的查询来做到这一点..

 echo $this->db->last_query();exit; //after query is made ..

以及您更新的问题..加入不正确..

更新

这个

$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
于 2013-01-21T11:07:27.240 回答