CodeIgniter内连接第3表

时间:2013-01-21 10:51:21

标签: php codeigniter

我在尝试添加第3张表时遇到了一些麻烦。

这是表结构:

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

感谢任何帮助

1 个答案:

答案 0 :(得分: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