如何在文件迭代期间将记录保存在 psql 中

How can I save records in psql during iteration in a file

我有一个只包含 id 的文件。该 ID 与 table 中的其中一列相匹配。我想提取该列中的记录并将结果保存在 csv 文件中。我不想创建另一个 table.

我有 docid.txt 包含以下数据的文件:

12000072
112073
11279
1182
11188
11182094
82099
11102

其中每一个都对应于学生 table 中的一个 nameid 列。学生 table 有:

name    nameid      dob         performance
-------------------------------------------
andre   12000072    12/4/1990   Excellent
Scott   112073      12/5/1999   Good
Reagan  2692882     15/7/2003   fair
Aldo    1402508     4/7/1998    Poor
Mary    2266257     5/11/1995   Very good
Walt    11182094    3/12/2000   Good
Tessy   82099       8/12/1999   Very good
Skinn   11102       7/2/2002    Excellent
Smart   678016      12/4/1990   fair
John    475689      12/5/1999   Poor
Rita    2796799    12/4/1990    Very good
Rachael 11188      12/5/1999    Poor
Gomez   3075168    3/12/2000    Very good
Becham  3075168    4/7/1998     Good
Walker  1050879    5/11/1995    Very good
Tommy   2017451    3/12/2000    Excellent
Trevor  11279      7/2/2002     Good
Litin   1182       12/5/1999    fair
Martha  883368     15/7/2003    fair
Rafael  3070833    4/7/1998     Poor
Kim     3070833    5/11/1995    Very good
Clichy  255918     12/4/1990    Good
Mario   2706915    12/5/1999    Excellent

我想从学生 table 中删除带有 docid 的学生。我尝试了以下方法:

for i in `cat docid.txt;` do
`psql -A -t $dbname $username << EOF`
`select * from student where nameid = $i;`
`EOF`
`done  >>docid.csv`

谢谢

假设您使用的是 PostgreSQL,我建议 copy将它们放入临时 table,然后加入。

例如

$ psql <<'__END__'
BEGIN;
CREATE TEMPORARY TABLE docids (docid integer) ON COMMIT DROP;
\copy docids from 'docids.txt'
DELETE FROM student USING docids WHERE nameid = docid;
COMMIT;
__END__

除了比循环更简洁、更简单之外,它的速度会更快,而且它会作为一个整体成功或失败,而不会留下半成品出现错误。

如果要输出删除的行,将RETURNING *附加到DELETE语句,运行加上psql -q以抑制其他输出。