SQL Server:选择多个表并显示关系,即使是NULL

时间:2016-09-19 08:15:22

标签: sql sql-server pivot-table

我有3张桌子。

问题表

___________________
id_issue | issue   |
1        | issue A |
2        | issue B |
3        | issue C |
___________________

问题表

_______________________
id_problem | problem   |
1          | problem A | 
2          | problem B |
3          | problem C |
_______________________

Visi表。

之前在2张桌子上有fk
__________________________________________
id_visi | visi   | id_problem | id_issue  |
1       | visi A |      1     |     1     |
2       | visi B |      1     |     2     |
3       | visi C |      1     |     3     |
4       | visi D |      2     |     1     |
5       | visi E |      2     |     2     |
___________________________________________

我想要像这样组合3个表。 : [编辑]

_____________________________________
| visi   | problem       | issue    |
| visi A | problem A     | issue A  |
| visi B | problem A     | issue B  |
| visi C | problem A     | issue C  |
| visi D | problem B     | issue A  |
| visi E | problem B     | issue B  |
| NULL   | problem B     | issue C  |
| NULL   | problem C     | issue A  |
| NULL   | problem C     | issue B  |
| NULL   | problem C     | issue C  |
_____________________________________

我曾尝试过JOIN表,但它没有用。结果没有显示NULL行。

1 个答案:

答案 0 :(得分:2)

您需要组合CROSS JOIN& LEFT JOIN

SELECT visi, 
       ip.id_problem, 
       ip.id_issue 
FROM   (SELECT * 
        FROM   issue I 
               CROSS JOIN problem P) ip 
       LEFT JOIN visi v 
              ON ip.id_problem = v.id_problem 
                 AND ip.id_issue = v.id_issue 

CROSS JOIN:填充两个表格之间的所有可能组合(Issue& Problem)。

LEFT JOIN:为VisiNULL的匹配记录提取不匹配记录的数据