将Select查询的结果存储在sql文件PSQL中以供以后使用
我有PostgreSQL数据库。我使用PSQL命令运行sql文件:将Select查询的结果存储在sql文件PSQL中以供以后使用,sql,postgresql,psql,postgresql-9.6,Sql,Postgresql,Psql,Postgresql 9.6,我有PostgreSQL数据库。我使用PSQL命令运行sql文件: psql --dbname=postgresql://postgres:password@127.0.0.1:port/dbname < filename.sql 但我有一个外键依赖项: “记录”外键(recordsinfoid)引用 recordsinfo(recordsinfoid) 因此,我不能在第二个delete语句中使用子查询,因为记录会在第一个delete语句中被删除 此外,我不能将第二个delete语句放在
psql --dbname=postgresql://postgres:password@127.0.0.1:port/dbname < filename.sql
但我有一个外键依赖项:
“记录”外键(recordsinfoid)引用
recordsinfo(recordsinfoid)
因此,我不能在第二个delete语句中使用子查询,因为记录会在第一个delete语句中被删除
此外,我不能将第二个delete语句放在第一位,因为它会导致外键冲突
如何删除recordsinfo中与子查询“从id=1的记录中选择recordsinfo”对应的所有条目?使用临时表作为记录缓冲区:
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);
将临时表用作记录缓冲区:
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);
使用游标从记录中获取recordsinfoid。 通过分隔“,”附加recordsinfoid来生成字符串。 使用创建的字符串进行删除查询, 使用exec()执行查询
我正在使用mssql。使用游标从记录中获取记录信息。 通过分隔“,”附加recordsinfoid来生成字符串。 使用创建的字符串进行删除查询, 使用exec()执行查询
我正在使用mssql。使用数据修改CTE:
with d as (
delete from records
where id = 1
returning *
)
delete from recordsinfo
where recordsinfoid in (select recordsinfoid from d);
使用数据修改CTE:
with d as (
delete from records
where id = 1
returning *
)
delete from recordsinfo
where recordsinfoid in (select recordsinfoid from d);
我用以下方法解决了这个问题:
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 $$;
基本上先预取数组中的值,然后再删除我使用以下方法解决它:
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 $$;
基本上先预取数组中的值,然后再删除