0

在第二个 SUB-SELECT 中保留 WHERE 子句是否更有效?双向工作,但我正在寻找使用此 SQL 语句最有效的方法......

表 2 t2 中有很多 substr(FIELD_G,10,3) 的记录和值,所以我不确定是否应该在左加入之前先在第二个 SUB-SELECT 中过滤掉它???

我的问题是我应该在 JOINING 之前过滤第二个 SUB-SELECT 中的结果还是应该消除 WHERE 子句(在第二个 SUB-SELECT 中),检索所有内容并依靠 LEFTJOIN 给我我的结果???

如果 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
  ;
4

2 回答 2

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;
于 2015-10-21T16:24:02.597 回答
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 ;
于 2016-03-16T12:42:24.603 回答