2017-05-08 80 views
0

我們的數據庫中有三種類型的用戶。我們正在嘗試生成報告。我可以把他們一起加入。但如果我這樣做,我有三個名字和三個姓氏列。我如何將所有三種數據合併到一列中。左連接三個表,將名稱字段組合成一列

SELECT e_job.objId AS 'Job Number', e_student.Lastname, e_student.Name, e_teachers.Lastname, e_teachers.Name, e_supportStaff.Lastname, e_supportStaff.Name 
FROM e_job 
LEFT JOIN e_student ON e_job.jName = e_student.username 
LEFT JOIN e_teachers ON e_job.jName = e_teachers.username 
LEFT JOIN e_supportStaff ON e_job.jName = e_supportStaff.username WHERE jStatus != 2 && jStatus != 7 && jStatus != -1 

當前輸出顯示7列,每種類型的用戶都有姓氏的第一個名字。

如何組合最後6列,以便所有名字都在1中,並且最後名稱在另一個名稱中。

------------------------------------- 
|Job Number |Last Name |Fist Name | 
|-----------|-----------|-----------| 
|1   |Doe  |John  | 
|2   |Test  |Test  | 
|3   |Test 2  |Test2  | 
------------------------------------- 

謝謝

+0

它是什麼數據庫? (這對可用解決方案有所不同)。始終在標籤中包含數據庫類型。 –

+0

mysql對不起,我沒有意識到。 –

+0

**順便說一句**不要使用單引號標識,請使用它們作爲值。例如對** AS「Last Name」**使用雙引號**,但是我個人從不使用帶空格的列名。 –

回答

1

一個通用的解決方案可能是一個聯合查詢是這樣的:

SELECT e_job.objId AS "Job Number", e_student.Lastname AS "Job Number", e_student.Name AS "First Name" 
FROM e_job 
INNER JOIN e_student ON e_job.jName = e_student.username 

UNION 

SELECT e_job.objId AS 'Job Number', e_teachers.Lastname, e_teachers.Name 
FROM e_job 
INNER JOIN e_teachers ON e_job.jName = e_teachers.username 

UNION 

SELECT e_job.objId AS 'Job Number', e_supportStaff.Lastname, e_supportStaff.Name 
FROM e_job 
INNER JOIN e_supportStaff ON e_job.jName = e_supportStaff.username WHERE jStatus != 2 && jStatus != 7 && jStatus != -1 

注意左聯接已改變爲內部連接becase的我們就不再需要迎合其他表和內部連接,我們只獲取具有匹配數據的行。

的選擇,如果你想的類型的人之間進行區分,然後介紹了另一列,並更改使用UNION ALL

SELECT e_job.objId AS "Job Number", 'Student' as Type, e_student.Lastname AS "Job Number", e_student.Name AS "First Name" 
FROM e_job 
INNER JOIN e_student ON e_job.jName = e_student.username 

UNION ALL 

SELECT e_job.objId AS 'Job Number', 'Teacher' as Type, e_teachers.Lastname, e_teachers.Name 
FROM e_job 
INNER JOIN e_teachers ON e_job.jName = e_teachers.username 

UNION ALL 

SELECT e_job.objId AS 'Job Number', 'Support' as Type, e_supportStaff.Lastname, e_supportStaff.Name 
FROM e_job 
INNER JOIN e_supportStaff ON e_job.jName = e_supportStaff.username WHERE jStatus != 2 && jStatus != 7 && jStatus != -1 

注意:從 UNION,單獨使用時,將刪除重複的行結果(因此可能比UNION ALL慢,不會刪除重複的行)。在我的第二個查詢中,你不能複製3個子查詢中的任何一行,因爲第2列在每個子查詢中都是不同的,UNION ALL是有意義的。