2017-08-18 60 views
-1

父表:我創建了3個表包含父母,子女,標誌着

Id int(primarykey), 
Firstname varchar(50), 
Email varchar(50) 

子表:

Mid int(primarykey), 
Mark1 int, 
Mark2 int, 
Id int(foreignkey) 

在標記表:

Uid int(primarykey), 
Mark3 int, 
Id int(foreignkey) 

我在用這個查詢:

select Id,Firstname,Mark1,Mark2,Mark3 
from 
(select Id,Firstname,Null as Mark1,Null as Mark2,Null as Mark3 from Parent 
union 
select Id,Null as Firstname,Mark1,Mark2,Null as Mark3 from Child 
union 
select Id,Null as Firstname,Null as Mark1,Null as Mark2,Mark3 from Mark)t 
group by Id,Firstname,Mark1,Mark2,Mark3 

,但如果我使用的ID,姓名,MARK-1,MARK2,MARK3按功能使組和我得到的結果是這樣

enter image description here

所以我需要的結果是這樣的,從而是可能的做?

enter image description here

+0

(如https://www.w3schools.com/sql/sql_union.asp)。不要使用名稱'id'作爲外鍵。通常我們使用' _id'作爲一個外鍵,所以像parent_id表子 – Jens

+0

預期結果背後的邏輯 – Jens

+0

請看看這個鏈接(https://spaghettidba.com/2015/04/24/how -to-post-at-sql-question-on-a-public-forum /)瞭解更多關於如何改善問題和不發佈圖片的信息 – TheGameiswar

回答

0

只是工會代替工會所有。

select Id,Firstname,Null as Mark1,Null as Mark2,Null as Mark3 from Parent 
union all 
select Id,Null as Firstname,Mark1,Mark2,Null as Mark3 from Child 
union all 
select Id,Null as Firstname,Null as Mark1,Null as Mark2,Mark3 from Mark 
0

你不應該使用UNION,但加入(如:https://www.w3schools.com/sql/sql_join.asp

SELECT A.Id, A.Firstname, B.MARK1, B.MARK2, C.MARK3 
FROM PARENT A 
LEFT JOIN CHILD B ON A.ID = B.ID 
LEFT JOIN MARK C ON A.ID = C.ID 

你可以找到很多的教程對SQL連接和SQL UNION