我正在尝试从表中复制数据并使用一些不同的字段插入其中。这里插入它时导致一个问题,我必须指定id(主键),它应该是自动递增但由于某种原因在创建表时没有设置为serial。我希望根据已存在的数据在要插入的数据中添加递增ID。
任何帮助将不胜感激。
self.file.writelines("%s,%s\n" % (u, o)
for u in item['Urls']
for o in item['output_urls'])
更新:
之前执行选择查询意味着要插入,取得以下结果。
WITH my_admin_id AS
(
SELECT id
FROM dashboard_admin
WHERE email = 'someone@somedomain.com'
),
get_admin AS
(
SELECT id
FROM dashboard_admin
WHERE user_id IN (SELECT id FROM auth_user WHERE username = 'demo')
),
get_admin_projects AS
(
SELECT *
FROM dashboard_project
WHERE admin_id IN (SELECT * FROM get_admin LIMIT 1)
AND is_deleted = 'false'
) INSERT INTO dashboard_project
(
SELECT id,
name,
created_date,
(SELECT * FROM my_admin_id LIMIT 1)AS admin_id,
category_id,
subcategory_id,
is_deleted FROM get_admin_projects
)
这里我刚刚添加了一个查询来获取最大ID。我只需要为最终选择查询中的每条记录增加它。
67 1stAd 2017-04-21 15:25:16.430889 100 18 47 false
71 2stAd 2017-05-12 10:18:55.383967 100 34 90 false
这是执行选择查询的结果值。
WITH my_admin_id AS
(
SELECT id
FROM dashboard_admin
WHERE email = 'someone@somedomain.com'
),
get_admin AS
(
SELECT id
FROM dashboard_admin
WHERE user_id IN (SELECT id FROM auth_user WHERE username = 'demo')
),
get_max_project AS
(
SELECT MAX(id) FROM dashboard_project
),
get_admin_projects AS
(
SELECT id,
name,
created_date,
admin_id,
category_id,
subcategory_id,
is_deleted
FROM dashboard_project
WHERE admin_id IN (SELECT * FROM get_admin LIMIT 1)
AND is_deleted = 'false'
) (SELECT (SELECT * FROM get_max_project) id,
name,
created_date,
(SELECT * FROM my_admin_id LIMIT 1) AS admin_id,
category_id,
subcategory_id,
is_deleted
FROM get_admin_projects)
答案 0 :(得分:0)
最后让它像这样工作使用了我添加到max id的row_number()窗口函数,以增加高于最大id的值。
WITH my_admin_id AS
(
SELECT id
FROM dashboard_admin
WHERE email = 'someone@somedomain.com'
),
get_admin AS
(
SELECT id
FROM dashboard_admin
WHERE user_id IN (SELECT id FROM auth_user WHERE username = 'demo')
),
get_max_project AS
(
SELECT MAX(id) FROM dashboard_project
),
get_admin_projects AS
(
SELECT id,
name,
created_date,
admin_id,
category_id,
subcategory_id,
is_deleted
FROM dashboard_project
WHERE admin_id IN (SELECT * FROM get_admin LIMIT 1)
AND is_deleted = 'false'
)
insert into dashboard_project (SELECT ((SELECT * FROM get_max_project) + row_number() over ()) as id,
name,
created_date,
(SELECT * FROM my_admin_id LIMIT 1) AS admin_id,
category_id,
subcategory_id,
is_deleted
FROM get_admin_projects)