连接性能较差的SQL查询

时间:2016-04-26 00:15:50

标签: sql oracle join oracle12c

我在为 Oracle 12c编写的查询中遇到了非常糟糕的表现。这可能与我对连接的低效使用有关,并且希望有人可以帮助我解决我出错的地方。我的查询目前需要一分钟才能运行

我正在尝试将表和列名称返回到:

  • 该列属于主键
  • 列类型为数字
  • 表格的所有者是 MY_OWNER
  • 主键是单列约束

目前我的查询内容如下

SELECT consCols.table_name, consCols.column_name 
FROM all_cons_columns consCols
INNER JOIN all_constraints cons 
  ON cons.constraint_name = consCols.constraint_name
INNER JOIN all_tab_columns cols 
  ON consCols.table_name = cols.table_name AND consCols.column_name = cols.column_name
WHERE cons.constraint_type = 'P' 
AND cons.owner = 'MY_OWNER'
AND cols.data_type = 'NUMBER'
AND consCols.table_name IN(
  SELECT consCols2.table_name 
  FROM all_cons_columns consCols2
  INNER JOIN all_constraints cons2 
    ON cons2.constraint_name = consCols2.constraint_name
  WHERE cons2.constraint_type = 'P' 
  AND cons2.owner = 'MY_OWNER' 
  GROUP BY consCols2.table_name
  HAVING COUNT(consCols2.table_name) = 1
);

感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:3)

使用分析函数会加快查询速度吗?

 $scope.checkJob= function(data) {

   //your logic

  };

甚至聚合?

SELECT table_name, column_name
FROM (SELECT consCols.table_name, consCols.column_name, cols.data_type,
             COUNT(*) OVER (PARTITION BY consCols.table_name) as cnt
      FROM all_cons_columns consCols INNER JOIN
           all_constraints cons 
           ON cons.constraint_name = consCols.constraint_name INNER JOIN
           all_tab_columns cols 
           ON consCols.table_name = cols.table_name AND consCols.column_name = cols.column_name
      WHERE cons.constraint_type = 'P' AND
            cons.owner = 'MY_OWNER'
     ) tc               
WHERE data_type = 'NUMBER' AND cnt = 1;

这是第三种选择:

  SELECT consCols.table_name, consCols.column_name
  FROM all_cons_columns consCols INNER JOIN
       all_constraints cons 
       ON cons.constraint_name = consCols.constraint_name INNER JOIN
       all_tab_columns cols 
       ON consCols.table_name = cols.table_name AND consCols.column_name = cols.column_name
  WHERE cons.constraint_type = 'P' AND
        cons.owner = 'MY_OWNER'
  GROUP BY consCols.table_name, consCols.column_name
  HAVING COUNT(*) = 1 AND
         MAX(cols.data_type) = 'NUMBER';

这消除了聚合,查找应该相对较快。