将Select查询的结果存储在SQL文件PSQL中以供以后使用

时间:2018-12-31 08:15:48

标签: sql postgresql psql postgresql-9.6

我有PostgreSQL数据库。我使用PSQL命令运行一个sql文件:

psql --dbname=postgresql://postgres:password@127.0.0.1:port/dbname < filename.sql

我的sql文件如下:

delete from records where id = 1;
delete from recordsinfo where recordsinfoid IN (select recordsinfoid from records where id = 1);

但是我有一个外键依赖项:

  

'records'外键(recordsinfoid)参考   recordsinfo(recordsinfoid)

所以我不能在第二条delete语句中有子查询,因为记录会在第一条delete语句中被删除。

我也不能放在第二个delete语句的前面,因为它会引起外键冲突。

如何删除recordsinfo中与子查询“从id = 1的记录中选择recordsinfoid”相对应的所有条目?

4 个答案:

答案 0 :(得分:1)

使用临时表作为记录缓冲区:

create temp table tmp_records
as
select recordsinfoid from records where id = 1;

delete from records where id = 1;
delete from recordsinfo where recordsinfoid IN (select recordsinfoid from tmp_records);

答案 1 :(得分:1)

使用修改数据的CTE:

with d as (
      delete from records
      where id = 1
      returning *
     )
delete from recordsinfo
    where recordsinfoid in (select recordsinfoid from d);

答案 2 :(得分:0)

使用光标从记录中获取recordsinfoid。 通过用','分隔附加recordsinfoid来创建字符串。 使用创建的字符串进行删除查询, 使用exec()执行查询

我正在使用mssql。

答案 3 :(得分:0)

我使用以下方法解决了该问题:

DO $$
DECLARE
    recordsinfoids INTEGER[];
    i INTEGER;
BEGIN

    recordsinfoids := ARRAY(select recordsinfoid from records where id = 1);

    delete from records where id = 1;

    FOREACH i IN ARRAY recordsinfoids
    LOOP 
        delete from recordsinfo where recordsinfoid = i;
    END LOOP;

END $$; 

基本上预取数组中的值,然后再删除

相关问题