【发布时间】:2017-01-06 15:36:30
【问题描述】:
我写了一个查询来检查记录是否存在,如果条件为真,它将更新,否则它将插入一条新记录。
问题是在插入时,它返回Query returned successfully: 1 rows affected, 200ms execution time.
但更新时返回“查询成功返回:0 行受影响,190 毫秒执行时间。”但该值已正确更新。
这里是创建表的示例脚本
CREATE TABLE sample
(
templateid integer NOT NULL DEFAULT nextval('checktemplate_language_lookup_seq'::regclass),
languageid integer NOT NULL,
templatetitle character varying(100),
disclaimer text,
createdby integer NOT NULL,
createdtimestamp timestamp without time zone NOT NULL DEFAULT ('now'::text)::timestamp without time zone,
updatedby integer,
updatedtimestamp timestamp without time zone,
CONSTRAINT sample_templateid_languageid UNIQUE (templateid, languageid)
)
在表中插入新记录:
WITH new_values (templateId, languageId, templatetitle, disclaimer, createdby,createdtimestamp,updatedby,updatedtimestamp)
AS (
VALUES (1, 1, 'LangTemplateTitle1', 'LangDisclaimer1', 1,current_timestamp,1,current_timestamp)
), upsert
AS (
UPDATE sample m
SET templatetitle = nv.templatetitle, disclaimer = nv.disclaimer, updatedby = nv.updatedby, updatedTimeStamp = nv.updatedtimestamp
FROM new_values nv
WHERE m.templateId = nv.templateId AND m.languageId = nv.languageId RETURNING m.*
)
INSERT INTO sample (templateId, languageId, templatetitle, disclaimer, createdby,createdtimestamp)
SELECT templateId, languageId, templatetitle, disclaimer, createdby ,createdtimestamp
FROM new_values
WHERE NOT EXISTS (
SELECT 1
FROM upsert up
WHERE up.templateId = new_values.templateId AND up.languageId = new_values.languageId
)
用不同的值更新同一行:(更新相同的查询值)
WITH new_values (templateId, languageId, templatetitle, disclaimer, createdby,createdtimestamp,updatedby,updatedtimestamp)
AS (
VALUES (1, 1, 'LangTemplateTitle2', 'LangDisclaimer2', 1,current_timestamp,1,current_timestamp)
), upsert
AS (
UPDATE sample m
SET templatetitle = nv.templatetitle, disclaimer = nv.disclaimer, updatedby = nv.updatedby, updatedTimeStamp = nv.updatedtimestamp
FROM new_values nv
WHERE m.templateId = nv.templateId AND m.languageId = nv.languageId RETURNING m.*
)
INSERT INTO sample (templateId, languageId, templatetitle, disclaimer, createdby,createdtimestamp)
SELECT templateId, languageId, templatetitle, disclaimer, createdby ,createdtimestamp
FROM new_values
WHERE NOT EXISTS (
SELECT 1
FROM upsert up
WHERE up.templateId = new_values.templateId AND up.languageId = new_values.languageId
)
即使我使用相同的查询进行更新,我如何获得“行数影响值”
【问题讨论】:
-
它从您的 INSERT 语句返回行数,即使没有要插入的记录,该语句仍在工作。所以你收到了这条信息。
-
我的问题是,当更新同一行时,它应该返回受影响的行数吗?
-
您需要更改您的查询。您只能看到最后一条语句的消息。 AND UPDATE 在 INSERT 之前。您可以使用 IF 或类似的东西。
-
其实,只有当记录正确存在时才会更新,所以如果记录已经存在则不会执行insert语句。
-
您的 INSERT 在任何情况下都可以使用。它只是不会插入任何东西,因为它的 SELECT 将返回 0 行。但是, INSERT 会起作用。它将插入 0 条记录。查看您的查询,在您的 INSERT 之前没有 IF 或类似的东西。因此它有效。
标签: sql postgresql