phpmysqlcodeigniteractiverecordleft-join

Left join quantity records and apply zero default when no joined record with CodeIgniter active record


I have 3 tables,

 itemmaster
|--------|----------|
|  id    |   name   |
|--------|----------|
|   1    |   Pizza  | 
|--------|----------|
|   2    |   Burger | 
|--------|----------|
|   3    |   Pepsi  | 
---------------------

     order
    |--------|----------|
    |orderid |   date   |
    |--------|----------|
    |   1    |   1-1-11 | 
    |--------|----------|
    |   2    |   2-1-11 | 
    |--------|----------|
    |   3    |   3-1-11 | 
    ---------------------


          orderdetails
        |--------|-------------|---------|---------|
        |  id    |   orderid   |itemid   |quantity |
        |--------|-------------|---------|---------|
        |   1    |   1         | 1       | 10      |
        |--------|-------------|---------|---------|
        |   2    |   1         | 2       | 20      |
        |--------|-------------|---------|---------|
        |   3    |   2         | 1       | 10      |
        -------------------------------------------

I want to join these 3 tables to get quantity of items of an order that placed on a particular date. What I have tried is:

$this->db->from('itemmaster');
$this->db->join('orderdetails', 'orderdetails.itemid= itemmaster.id','left');
$this->db->join('order', 'order.orderid= orderdetails.orderid');
$this->db->where('order.date',"1-1-11");            
$query = $this->db->get();

I got result as:

Pizza------ 10
Burger------10

What I want is:

Pizza-------10
Burger------20
Pepsi-------0

Solution

  • If changing the all the joins to left joins, you can always do it in two separate query and do a union between the two of them. One would get all the lines that actualy have a quantity and the other would get the rests and put them toguether.

    It would look a bit like this. there might be some synthax error, but you'll have to rewrite it in php anyway:

    p.s. to add up the quantities, you can use sum()

    Select itemmaster.name, orderdetails.quantity from itemmaster 
    left join orderdetails on orderdetails.itemid = itemmaster.id 
    left join order on order.orderid = orderdetails.orderid 
    where order.date = '1-1-11'
    group by itemmaster.name
    
    Union 
    Select itemmaster.name, '0' as quantity From itemmaster 
    except (Select itemmaster.name, orderdetails.quantity from itemmaster 
    left join orderdetails on orderdetails.itemid = itemmaster.id 
    left join order on order.orderid = orderdetails.orderid 
    where order.date = '1-1-11'
    group by itemmaster.name)
    group by itemmaster.name
    

    hope this helps ! good luck