我创建了3个包含父,子,标记的表

时间:2017-08-18 07:45:40

标签: sql-server sql-server-2008

在父表中:

# Compute the installation prefix relative to this file.
get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)

在子表中:

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)

但如果我使用id,firstname,mark1,mark2,mark3按功能制作分组,我就会得到这样的结果

enter image description here

所以我需要结果是这样的,那可能吗?

enter image description here

2 个答案:

答案 0 :(得分:0)

只需用union all替换union。

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

答案 1 :(得分:0)

你不应该使用UNION,而是加入:

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 join的教程(例如https://www.w3schools.com/sql/sql_join.asp)和SQL UNION(例如https://www.w3schools.com/sql/sql_union.asp