Suppose I have three tables
crew
+------------+----------+-------------------------+
| EmployeeID | FlightNo | DepartureTime |
+------------+----------+-------------------------+
| 2 | AA123 | 2018-12-30 09:30:45 |
| 7 | AA123 | 2018-12-30 09:30:45 |
| 8 | AA123 | 2018-12-30 09:30:45 |
employeetype
+----------------+-----------------+
| EmployeeTypeID | Name |
+----------------+-----------------+
| 1 | Pilot |
| 2 | First Officer |
| 3 | Stewardess |
and employee
+------------+-----------+----------------+
| EmployeeID | Name | EmployeeTypeID |
+------------+-----------+----------------+
| 2 | James | 2 |
| 3 | Alexandra | 3 |
| 4 | Alina | 2 |
| 6 | Peter | 2 |
| 7 | NULL | 3 |
| 8 | John | 1 |
| 9 | Frank | 1 |
I have joined these three tables but for EmployeeID 7 where the Name is NULL I don't get the NULL value using left join
select crew.FlightNo, group_concat(distinct(crew.DepartureDateAndTimeUTC) separator ',') as time, group_concat(employee.Name separator ',') as crew,group_concat(distinct(employeetype.Name)separator ',') as type
from employee
left join crew on employee.EmployeeID = crew.EmployeeID
inner join employeetype
on employeetype.EmployeeTypeID = employee.EmployeeTypeID group by crew.FlightNo;
But I don't get the Null in the crew column
+----------+---------------------+---------------------------------+----------------------------------+
| FlightNo | time | crew | type |
+----------+---------------------+---------------------------------+----------------------------------+
| AA123 | 2018-12-30 09:30:45 | James,John | Pilot,First Officer, Stewardess |
I want in the crew column James, John, NULL
I think you intend:
select c.FlightNo,
group_concat(distinct c.DepartureDateAndTimeUTC) separator ',') as time,
group_concat(e.Name separator ',') as crew,
group_concat(distinct et.Name) separator ',') as type
from crew c left join
employee e
on e.EmployeeID = c.EmployeeID left join
employeetype et
on et.EmployeeTypeID = e.EmployeeTypeID
group by c.FlightNo;
Usually in a query with left join
s, you need to keep using them. In this case, I think you want to start with crew
, because you are aggregating by FlightNo
. I don't know why you would want a row for employees that are not on any flights.
The other issue is that group_concat()
ignores NULL
values. If you want to see them, use coalesce()
:
group_concat(coalesce(e.Name, '') separator ',') as crew,
or perhaps:
group_concat(coalesce(e.Name, '<NULL>') separator ',') as crew,