我试图在postgresql中执行几个命令,我通过命令行支付,但它只从第二个返回结果:
psql -d data1 -U user123 -c "select count(*) from table1; select count(*) from table2;"
而当我登录" psql"并运行相同的命令,我得到2个结果集。
为什么它不起作用?
答案 0 :(得分:1)
psql --help
给出(部分)
-c, --command=COMMAND run only single command (SQL or internal) and exit
这里有两个命令,可以获得combine the queries所需的两个结果(UNION
);像
psql -d data1 -U user123 -c \
"select count(*) from table1 UNION ALL select count(*) from table2;"
或,运行两个命令(查询)
psql -d data1 -U user123 -c "select count(*) from table1;"
psql -d data1 -U user123 -c "select count(*) from table2;"
或,您可以将两个命令放在一个文件中并使用-f
(psql --help
说明)
-f, --file=FILENAME execute commands from file, then exit
答案 1 :(得分:0)
使用管道:
$ echo "
> select 1;
> \d
> " | psql # here is the magic, happy New Year *~<:o)
╔══════════╗
║ ?column? ║
╠══════════╣
║ 1 ║
╚══════════╝
(1 row)
List of relations
╔════════╤════════════════════╤══════╤══════════╗
║ Schema │ Name │ Type │ Owner ║
╠════════╪════════════════════╪══════╪══════════╣
║ public │ dummy │ view │ postgres ║
║ public │ pg_stat_statements │ view │ nd ║
╚════════╧════════════════════╧══════╧══════════╝