在创建列管理工具时,我遇到了在 PostgreSQL 中快速复制表的需要,因此我不会使用非测试表来测试新工具。为了有效地测试我最终打算在表上使用的新列工具,parts
我创建了这个新工具来复制parts
,这样我最终会得到一个parts1
表。当我以为我终于解决了所有问题时,当列工具删除表时,我遇到了以下错误:
错误:无法删除表部分,因为其他对象依赖于它详细信息:表 parts1 列 id 的默认值取决于序列 parts_id_seq1
我花了一天的大部分时间来研究这个解决方案,所以简而言之,我可以简单地使用字符串函数来重命名变量以将表与表SEQUENCE_NAME
分离,还是这是一个比这更复杂的问题?这是查询:parts
parts
DO $$
DECLARE
SEQUENCE_NAME VARCHAR;
BEGIN
SELECT s.relname INTO SEQUENCE_NAME
FROM pg_class AS s JOIN pg_depend d ON d.objid = s.oid
INNER JOIN pg_class AS t ON d.objid = s.oid AND d.refobjid = t.oid
INNER JOIN pg_attribute AS a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
INNER JOIN pg_namespace AS n ON n.oid = s.relnamespace
WHERE s.relkind = 'S' …
Run Code Online (Sandbox Code Playgroud) 我需要复制同一个表中的记录,只更改一个字段。我的表有默认生成的序列entry_id_seq
,但是我不确定id
列是 SERIAL(如何检查?)。
\d tab
只返回这个
Column | Type | Modifiers
-----------------+--------------------------------+------------------------
id | integer | not null
...
Indexes:
"tab_entry_pkey" PRIMARY KEY, btree (id)
Run Code Online (Sandbox Code Playgroud)
所以问题是:当我尝试以简化的方式复制记录时:
insert into tab_entry select * from tab_entry where id = 3052;
Run Code Online (Sandbox Code Playgroud)
它抛出错误
ERROR: duplicate key value violates unique constraint "tab_entry_pkey"
DETAIL: Key (id)=(3052) already exists.
Run Code Online (Sandbox Code Playgroud)
默认情况下,默认序列不会生成下一个值。是否有任何简洁的语法允许在没有完整表规范的情况下插入和更改单个字段FROM tab(col1, col2, col3, ..., col N)
?
该表有很多字段,所以我不想把它们都写出来,因为这会影响代码的可读性。我想要这样的东西,但这种语法不起作用
insert into tab_entry(id, *) select nextval('seq'), * from tab_entry where id = 3052;
Run Code Online (Sandbox Code Playgroud)
SELECT …
我已经啮合在一起的方式来确定什么data_type
是在data_type
创建基于掀起了新表时,你的语法使用PostgreSQL的维基页面。
如果我的查询有问题,我需要真正知道在给定场景中什么会在显式上下文中抛出它在纯粹的测试数据库/表上运行一个或多个查询以修改该数据库/表,所以运行这个查询以测试任何误报。
SELECT pg_attribute.attname,
format_type(pg_attribute.atttypid, pg_attribute.atttypmod),
CASE
WHEN format_type(pg_attribute.atttypid, pg_attribute.atttypmod)='bigint' THEN 'bigserial'
WHEN format_type(pg_attribute.atttypid, pg_attribute.atttypmod)='integer' THEN 'serial'
END AS type
FROM pg_index, pg_class, pg_attribute
WHERE pg_class.oid = 'delete2'::regclass
AND indrelid = pg_class.oid
AND pg_attribute.attrelid = pg_class.oid
AND pg_attribute.attnum = any(pg_index.indkey)
AND indisprimary;
Run Code Online (Sandbox Code Playgroud)
这是一个带有主键的表,该表不使用此查询返回主键:
CREATE TABLE delete_key_bigserial (
test1 integer,
id bigserial NOT NULL,
col1 text,
col2 text,
test2 integer
);
Run Code Online (Sandbox Code Playgroud)