【发布时间】:2019-03-12 18:08:40
【问题描述】:
我重写了一个查询来连接表而不是执行子查询,因为我需要查找大约 10 个数字,而 10 个子查询存在一点性能问题。
为简单起见更改了表名和列 *
查询以前是这样做的:
SELECT t1.col1, t1.col2, t1.col3,
(SELECT COUNT(j1.j_id) FROM jointable1 as j1 WHERE t1.t_employee_id = j1.j_employee_id
AND t1.t_week_ending = j1.j_week_ending AND j1.j_reason <> 'DNC') as col4,
(SELECT COUNT(j2.j_id) FROM jointable1 as j2 WHERE t1.t_employee_id = j2.j_employee_id
AND t1.t_week_ending = j2.j_week_ending) as col5
FROM table1 as t1
GROUP BY t1.col1, t1.col2, t1.col3;
我已经改写成这样了:
SELECT t1.col1, t1.col2, t1.col3, COUNT(j1.j_id) as col4, COUNT(j2.o_id) as col5
FROM table1 as t1
LEFT JOIN jointable1 as j1 ON (t1.t_employee_id = j1.j_employee_id
AND t1.t_week_ending = j1.j_week_ending)
AND j1.j_reason = <> 'DNC'
GROUP BY t1.col1, t1.col2, t1.col3;
问题是在上面的例子中为 col4 和 col5 返回的值很好。假设他们返回 7 和 8。
+------+------+------+------+--+
| col1 | col2 | col3 | col4 | |
+------+------+------+------+--+
| 1 | 0 | 0 | 34 | |
| 0 | 3 | 3 | 9 | |
| 7 | 1 | 0 | 2 | |
| 3 | 2 | 2 | 9 | |
| 4 | 1 | 0 | 4 | |
| 1 | 11 | 1 | 4 | |
| 5 | 2 | 5 | 21 | |
| 2 | 3 | 0 | 3 | |
| 2 | 3 | 0 | 2 | |
+------+------+------+------+--+
但在底部查询中,它们返回平方或乘以自身。所以 7 变成 49,8 变成 64。
+------+------+------+------+--+
| col1 | col2 | col3 | col4 | |
+------+------+------+------+--+
| 1 | 0 | 0 | 1156 | |
| 0 | 3 | 3 | 81 | |
| 7 | 1 | 0 | 16 | |
| 3 | 2 | 2 | 81 | |
| 4 | 1 | 0 | 16 | |
| 1 | 11 | 1 | 16 | |
| 5 | 2 | 5 | 441 | |
| 2 | 3 | 0 | 9 | |
| 2 | 3 | 0 | 4 | |
+------+------+------+------+--+
我不知道它是 LEFT JOIN 还是 GROUP BY 函数中缺少的东西,但是任何纠正的帮助都会很棒,或任何帮助重写一个更有效的方式也很棒。
【问题讨论】:
-
您能给我们展示一些示例表数据和预期结果吗? (格式化文本,而不是图像。)另请查看stackoverflow.com/help/mcve。
标签: sql sql-server database