假设我有三个表
船员
+------------+----------+-------------------------+
| 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 |
员工类型
+----------------+-----------------+
| EmployeeTypeID | Name |
+----------------+-----------------+
| 1 | Pilot |
| 2 | First Officer |
| 3 | Stewardess |
和员工
+------------+-----------+----------------+
| EmployeeID | Name | EmployeeTypeID |
+------------+-----------+----------------+
| 2 | James | 2 |
| 3 | Alexandra | 3 |
| 4 | Alina | 2 |
| 6 | Peter | 2 |
| 7 | NULL | 3 |
| 8 | John | 1 |
| 9 | Frank | 1 |
我已经加入了这三个表,但是对于名称为NULL的EmployeeID 7,我没有使用左联接获得NULL值
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;
但是我在乘员列中没有得到空值
+----------+---------------------+---------------------------------+----------------------------------+
| FlightNo | time | crew | type |
+----------+---------------------+---------------------------------+----------------------------------+
| AA123 | 2018-12-30 09:30:45 | James,John | Pilot,First Officer, Stewardess |
我想在剧组栏目James,John,NULL
答案 0 :(得分:2)
我认为您打算这样做
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;
通常在有left join
个查询的情况下,您需要继续使用它们。在这种情况下,我认为您想从crew
开始,因为您正在按FlightNo
进行汇总。我不知道您为什么要为不在任何航班上的员工排位。
另一个问题是group_concat()
忽略了NULL
的值。如果要查看它们,请使用coalesce()
:
group_concat(coalesce(e.Name, '') separator ',') as crew,
或者也许:
group_concat(coalesce(e.Name, '<NULL>') separator ',') as crew,