我的左联接在行中返回重复的键

时间:2020-03-18 07:22:29

标签: sql sql-server left-join

this my query and    

 SELECT MAIL_STONE.MailStoneName,MAIN_TASK.MainTaskName
    FROM   PROJECTS
    left JOIN MAIL_STONE
    On PROJECTS.ProjectsId = MAIL_STONE.ProjectsId
    left Join MAIN_TASK
    On MAIL_STONE.MailStoneId = MAIN_TASK.MailStoneId
    where PROJECTS.ProjectsId = 1132

这是结果

MailStone3                                                              task1                                                                 
MailStone3                                                              task2                                                                 
MailStone4                                                              NULL
MailStone1                                                              NULL
Specifications                                                          NULL

但是我需要使用左连接的结果

MailStone3    task1 task2                                                                  
MailStone4     NULL  NULL                                                       
MailStone1     NULL   NULL   

有人有主意吗?

2 个答案:

答案 0 :(得分:2)

尝试使用DISTINCT:

SELECT  DISTINCT 
MAIL_STONE.MailStoneId,MAIL_STONE.MailStoneName,MAIN_TASK.MainTaskName
FROM   PROJECTS
left JOIN MAIL_STONE
On PROJECTS.ProjectsId = MAIL_STONE.ProjectsId
left Join MAIN_TASK
On MAIL_STONE.MailStoneId = MAIN_TASK.MailStoneId
where PROJECTS.ProjectsId = 1132

答案 1 :(得分:0)

在下面的(DBfiddle)中尝试此查询

SELECT MAIL_STONE.MailStoneId ,
       MAIL_STONE.MailStoneName ,
       MAIN_TASK.MainTaskName
FROM PROJECTS
LEFT JOIN MAIL_STONE ON PROJECTS.ProjectsId = MAIL_STONE.ProjectsId
LEFT JOIN MAIN_TASK ON MAIL_STONE.MailStoneId = MAIN_TASK.MailStoneId
WHERE PROJECTS.ProjectsId = 1132
GROUP BY MAIL_STONE.MailStoneId ,
         MAIL_STONE.MailStoneName ,
         MAIN_TASK.MainTaskName