SQL:将查询发送到所有可用的数据库

时间:2015-08-19 07:37:18

标签: sql postgresql join

如何向服务器上的所有数据库发送查询?我不想输入所有数据库名称,脚本应该自动检测它们。

示例查询:

SELECT SUM(tourney_results.amt_won)-SUM((tourney_summary.amt_buyin+tourney_summary.amt_fee)) as results
FROM tourney_results
INNER JOIN tourney_summary
ON tourney_results.id_tourney=tourney_summary.id_tourney
Where id_player=(SELECT id_player FROM player WHERE player_name='Apple');

所以我想在这里实现,如果有2个数据库,第一个将产生60,第二个将产生50,我需要55输出。

所有数据库都具有相同的结构,表等。

1 个答案:

答案 0 :(得分:0)

您可以使用plpgsql和db_link来完成。首先在要连接的数据库中安装db_link扩展:

CREATE EXTENSION dblink;

然后使用plpgsql函数迭代服务器上的所有数据库并执行查询。请参阅此示例(请参阅内联注释)。请注意,我在函数中使用了示例查询。您必须使用真实查询调整该函数:

CREATE or REPLACE FUNCTION test_dblink() RETURNS BIGINT AS
  $$
DECLARE pg_database_row record;
        query_result BIGINT;
        _dbname TEXT;
        _conn_name TEXT;
        return_value BIGINT;
BEGIN
    --initialize the final value
    return_value = 0;
    --first iterate over the records in the meta table pg_database
    FOR pg_database_row in SELECT * FROM pg_database WHERE (NOT datistemplate) AND (datallowconn) LOOP

      _dbname = pg_database_row.datname;
      --build a connection name for db_link
      _conn_name=_dbname||'myconn';
      --close the connection is already active:
      IF array_contains(dblink_get_connections(),_conn_name) THEN
        PERFORM dblink_disconnect(_conn_name);
      END IF;

      -- open the connection with the actual database name
      PERFORM dblink_connect(_dbname||'myconn', 'dbname='||_dbname);
      -- check if the table does exist in the database:
      PERFORM * FROM dblink(_conn_name,'SELECT 1 from pg_tables where tablename = ''your_table''') AS t(id int) ;
      IF FOUND THEN
        -- if the table exist, perform the query and save the result in a variable
        SELECT * FROM dblink(_conn_name,'SELECT sum(id) FROM your_table limit 1') AS t(total int) INTO query_result;
         IF query_result IS NOT NULL THEN
           return_value = return_value + query_result;
         END IF;
      END IF;
      PERFORM dblink_disconnect(_conn_name);

    END LOOP;
RETURN return_value;
END;
    $$
  LANGUAGE 'plpgsql';

使用

执行该功能
select test_dblink();