即使JOIN表中不存在行,也能获得结果

时间:2017-11-14 20:32:36

标签: mysql azure

我存储了2种不同的备份类型(完整或日志),并且还有2种不同的服务器类型(本地或Azure),下面的查询会返回正确的结果,因为返回3行,但是当我删除对应于此的行时SQL查询中的行:

AND (r4.Type = 'Full' AND r4.Server = 'Azure')

然后只检索了2行,因为它们不是表中存在的类型为“Full”且服务器“Azure”

的行

这是我已经完成的查询:

SELECT DISTINCT
   r1.Tenant,
   r1.Name,
   r1.DBName,
   r1.Server as Server1,
   r1.Type as Type1,
   r1.Date as Date1,
   r2.Type as Type2,
   r2.Date as Date2,
   r2.Server as Server2,
   r3.Type as Type3,
   r3.Date as Date3,
   r3.Server as Server3,
   r4.Type as Typ4,
   r4.Date as Date4,
   r4.Server as Server4
FROM #Results AS r1
JOIN #Results AS r2 ON r2.DBName = r1.DBName 
JOIN #Results AS r3 ON r3.DBName = r1.DBName 
JOIN #Results AS r4 ON r4.DBName = r1.DBName 
WHERE
(r1.TYPE = 'Full' AND r1.Server = 'Local') AND
(r2.TYPE = 'Log' AND r2.Server = 'Local') AND
(r3.Type = 'Full' AND r3.Server = 'Azure') AND
(r4.Type = 'Log' AND r4.Server = 'Azure')
ORDER BY r1.Tenant

enter image description here

从上面的屏幕截图中可以看出,这是检索到的数据。我期待另一行包含以下内容:

  • Log,Local
  • 完整,本地
  • Log,Azure
  • NULL,NULL(不存在完整Azure备份)

以下是结果表中的数据:

enter image description here

2 个答案:

答案 0 :(得分:1)

您将需要使用LEFT JOIN,因为当r3和r4为空时,您仍然需要r1和r2的结果行。

您可能尝试修改所有JOIN个参数,但结果相同......这就是问题所在。当你尝试:

SELECT * FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.id = t2.t1_id
WHERE t2.some_column = 'a value'

LEFT JOIN正常工作,并返回一个空值为t2的行,但是这行在WHERE子句中被抛弃。 t2.some_column = 'a value'因为t2.some_column = NULL

,所以不可能

解决方案:

SELECT * FROM table_1 t1
LEFT JOIN table_2 t2 ON t1.id = t2.t1_id AND t2.some_column = 'a value'

现在任何没有'some_column ='值'的t2行不会被包含在结果集中,但是没关系,因为我们正在使用LEFT JOIN,因此该行将包含具有NULL t2值的t1值

或者您可以尝试:WHERE t2.is IS NULL OR t2.some_column = 'a value'

关于您的查询:

```select ... 
FROM #Results AS r1 
LEFT JOIN #Results AS r2 ON r2.DBName = r1.DBName AND (r2.TYPE = 'Log' AND r2.Server = 'Local') 
LEFT JOIN #Results AS r3 ON r3.DBName = r1.DBName AND (r3.Type = 'Full' AND r3.Server = 'Azure') 
LEFT JOIN #Results AS r4 ON r4.DBName = r1.DBName AND (r4.Type = 'Log' AND r4.Server = 'Azure') 
WHERE (r1.TYPE = 'Full' AND r1.Server = 'Local') 
ORDER BY r1.Tenant```

答案 1 :(得分:1)

$(".submit-btn").click(function(e) {
  e.preventDefault();
  var $this = $(this);
  if ($('#place-form-item').valid()) {
    $this.parents(".form-wrap").hide();
    $this.parents(".place-form").find(".success-msg").show();
  }
});

我删除了Server1 Server2列......因为它已经是日期信息的一部分。但如果需要它可以添加它。