简体   繁体   中英

MySQL list all records in left table with Join

I have two tables, one includes vehicle data & other includes fuel data as follows:

tbl_vehicle

+------------+--------+
| vehicle_id | reg_no |
+------------+--------+
|          1 | ABC    |
|          2 | DEF    |
|          3 | GHI    |
|          4 | JKA    |
|          5 | LMN    |
|          6 | OPQ    |
+------------+--------+

tbl_direct_fuel

+---------+------------+----------+------------+
| fuel_id | vehicle_id | fuel_qty |    date    |
+---------+------------+----------+------------+
|     100 |          1 |       10 | 2019-10-01 |
|     101 |          1 |       12 | 2019-10-02 |
|     102 |          2 |       20 | 2019-10-03 |
|     103 |          3 |       15 | 2019-10-03 |
|     104 |          2 |       25 | 2019-10-04 |
+---------+------------+----------+------------+

I tried to get all records of left table with relevant records of right table. Used following Query.

select("reg_no,sum(fuel_qty) as total")
            ->from('tbl_direct_fuel')
            ->join('tbl_vehicle', 'tbl_direct_fuel.vehicle=tbl_vehicle.vehicle_id', 'left')
            ->group_by ('reg_no')

The above code shows only the following output.

+--------+----------+
| reg_no | total    |
+--------+----------+
| ABC    |       22 |
| DEF    |       45 |
| GHI    |       15 |
+--------+----------+

But I need all the vehicles with un-fueled vehicles as follows.

Desired output

+--------+----------+
| reg_no | total    |
+--------+----------+
| ABC    |       22 |
| DEF    |       45 |
| GHI    |       15 |
| JKA    |        0 |
| LMN    |        0 |
| OPQ    |        0 |
+--------+----------+

You would to invert the tables in the left join , so that vehicules with no fueling do appear in the resultset (as it is, your left join allows for fueling without vehicules, which does not look like a relevant use case).

I would also recommend prefixing the column names with the table they come from to avoid ambiguity.

Finally, to return 0 (instead of null ) for the vehicules that had no fueling, you can use coalesce() .

select("tbl_vehicle.reg_no, coalesce(sum(fuel_qty), 0) fuel_qty")
    ->from('tbl_vehicle')
    ->join('tbl_direct_fuel', 'tbl_direct_fuel.vehicle = tbl_vehicle.vehicle_id', 'left')
    ->group_by ('tbl_vehicle.vehicle_id')

Try:

select t1.reg_no, t2.fuel_total
from tbl_vehicle t1
left join (
    select vehicle_id, sum(fuel_qty) fuel_total
    from tbl_direct_fuel
    group by vehicle_id
) t2 on t1.vehicle_id = t2.vehicle_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM