为了将值插入表中,我需要读取该表的最后一个主键值并从那里开始我的序列。但是我收到了一个错误。 我的查询如下:
CREATE SEQUENCE serial START(
SELECT cd.id + 1
FROM cd
ORDER BY cd.id DESC
LIMIT 1);
INSERT INTO cd(id, class)
SELECT (nextval('serial'), (
SELECT class_name
FROM another_table
WHERE some_condition
)
FROM cr
DROP SEQUENCE IF EXISTS serial;
错误如下:
ERROR: syntax error at or near "("
LINE 1: CREATE SEQUENCE serial START( SELECT cd.id + 1 FROM cd
如何获取主键的最后一个值并从那里开始我的序列?
我不允许更改表格设计,因此我无法为表格的主键定义序列。
答案 0 :(得分:0)
好吧,我解决了我的问题:
BEGIN TRANSACTION;
CREATE SEQUENCE serial START 1;
INSERT INTO cd(id, class)
SELECT (nextval('serial') + (select max(id)+1 from cd), (
SELECT class_name
FROM another_table
WHERE some_condition
)
FROM cr
DROP SEQUENCE IF EXISTS serial;
COMMIT;