在第二个SUB-SELECT中保留WHERE子句是否更有效。两种方式都可以,但我正在寻找这种SQL语句最有效的方法......
表2中有很多substr(FIELD_G,10,3)的记录和值,所以我不确定是否应该在离开加入之前先在第二个SUB-SELECT中对其进行过滤???
我的问题是我应该在JOINING之前过滤第二个SUB-SELECT中的结果还是应该消除WHERE子句(在第二个SUB-SELECT中),检索所有内容并依赖LEFTJOIN来给我结果??? < / p>
如果CNT等于0 - 我仍然需要返回t1.FIELD_A,t1.FIELD_B,t1.FIELD_C,t1.FIELD_D字段......
SELECT t1.FIELD_A, t1.FIELD_B, t1.FIELD_C, t1.FIELD_D, t2.CNT FROM (
SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D
FROM SCHEMA.TABLE_A
WHERE FIELD_A IN ('Z1','Z2','Z3','Z4','Z5','Z6','Z7','Z8','Z9','Z10','Z11','Z12','Z13','Z14','Z15','Z16','Z17','Z18','Z19','Z20','Z21','Z22')
) t1
LEFT JOIN
(
SELECT FIELD_A, COUNT(FIELD_A) AS CNT FROM (
SELECT substr(FIELD_G,10,3) AS FIELD_A
FROM SCHEMA.TABLE_B
WHERE substr(FIELD_G,10,3) IN ('Z1','Z2','Z3','Z4','Z5','Z6','Z7','Z8','Z9','Z10','Z11','Z12','Z13','Z14','Z15','Z16','Z17','Z18','Z19','Z20','Z21','Z22')
) GROUP BY FIELD_A
) t2
ON t1.FIELD_A = t2.FIELD_A
ORDER BY t1.FIELD_A
;
答案 0 :(得分:0)
您正尝试使用过滤器获取查询中的聚合值。问题是聚合是在所有数据上完成的,而不是在过滤后的子集上完成的。因此,您的查询会重复标准。
另一种方法是相关子查询:
SELECT t1.FIELD_A, t1.FIELD_B, t1.FIELD_C, t1.FIELD_D,
(SELECT COUNT(*)
FROM SCHEMA.TABLE_B b
WHERE substr(b.FIELD_G, 10, 3) = t1.FIELD_A
) as cnt
FROM SCHEMA.TABLE_A t1 LEFT JOIN
WHERE t1.FIELDA IN ('Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6', 'Z7', 'Z8', 'Z9', 'Z10',
'Z11', 'Z12', 'Z13', 'Z14', 'Z15', 'Z16', 'Z17', 'Z18', 'Z19', 'Z20',
'Z21', 'Z22')
ORDER BY t1.FIELD_A;
答案 1 :(得分:0)
您可以尝试此查询
SELECT t1.FIELD_A, t1.FIELD_B, t1.FIELD_C, t1.FIELD_D, t2.CNT
FROM SCHEMA.TABLE_A t1
LEFT JOIN (
SELECT FIELD_A, COUNT(FIELD_A) AS CNT FROM (
SELECT substr(FIELD_G,10,3) AS FIELD_A
FROM SCHEMA.TABLE_B ) GROUP BY FIELD_A
) t2
ON t1.FIELD_A = t2.FIELD_A
WHERE t1.FIELD_A IN ('Z1','Z2','Z3','Z4','Z5','Z6','Z7','Z8','Z9','Z10','Z11','Z12','Z13','Z14','Z15','Z16','Z17','Z18','Z19','Z20','Z21','Z22')
ORDER BY t1.FIELD_A ;