簡體   English   中英

左聯接不返回Null值

[英]Left join doesn't return the Null value

假設我有三個桌子

船員

+------------+----------+-------------------------+
| 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;

但是我在乘員列中沒有得到Null

+----------+---------------------+---------------------------------+----------------------------------+
| FlightNo | time                | crew                            | type                             |
+----------+---------------------+---------------------------------+----------------------------------+
| AA123    | 2018-12-30 09:30:45 | James,John                      | Pilot,First Officer, Stewardess  |

我想要在劇組專欄中James,John,NULL

我認為您打算:

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 s的查詢中,您需要繼續使用它們。 在這種情況下,我認為您想從crew入手,因為您正在按FlightNo進行匯總。 我不知道您為什么要為不在任何航班上的員工排位。

另一個問題是group_concat()忽略NULL值。 如果要查看它們,請使用coalesce()

   group_concat(coalesce(e.Name, '') separator ',') as crew,

也許:

   group_concat(coalesce(e.Name, '<NULL>') separator ',') as crew,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM