[英]update two tables at the same time postgresql
我在POSTGRESQL中有问题。
我想同时更新两个表。 两种更新都可以应用,因为它们具有相同的条件。
这是个人更新:
UPDATE standards.standards
SET description = 'The student will demonstrate positive self esteem.'
WHERE description LIKE 'The student will demonstrate positive his/her self esteem.'
AND custom_code LIKE 'qwertyuiop';
UPDATE bank SET description = 'The student will demonstrate positive self esteem.'
WHERE description LIKE 'The student will demonstrate positive his/her self esteem.'
AND designation LIKE 'asdfghjkl';
我只想在一个sql语句中更新它们。 这是我做的事情,但由于POSTGRESQL不允许同时更新两个表而出现错误。
UPDATE standards.standards ss, bank bb
SET description = 'The student will demonstrate positive self esteem.'
WHERE description LIKE 'The student will demonstrate positive his/her self esteem.'
AND (ss.custom_code LIKE 'qwertyuiop' OR bb.designation LIKE 'asdfghjkl');
你能帮我吗? 我只需要一个sql语句。 谢谢!
这样做是没有意义的,因为无论如何您都不会自动实现它。 它不会解决无法用更好的方法解决的任何问题(例如,如果您不想发送两次,则使用参数作为值)。
例如,您可以使用视图一次更新两个表。 但同样,它不会是原子的。 您仍然需要适当的事务处理,以确保它能够按预期工作。
您可以为此编写一个FUCTION ,请考虑您的当前信息。 作为一个例子来展示
create table standards (description text,custom_code text);
insert into standards
values ('hai','AA'),
('how are you ?','AA'),
('The student will demonstrate positive his/her self esteem.','qwertyuiop');
create table bank (description text,designation text);
insert into bank
values ('Am','BB'),
('Fine','BB'),
( 'The student will demonstrate positive his/her self esteem.' ,'asdfghjkl');
创造这样的温控功能
create or replace function update_tables(_desc text, /*-- your value to update i.e The student will demonstrate positive self esteem.*/
_WDesc text, /*-- your value to use in where clause i.e 'The student will demonstrate positive his/her self esteem.' */
_custom_code text, /* this AND custom_code LIKE 'qwertyuiop'; goes here */
_designation text /* this AND designation LIKE 'asdfghjkl'; goes here*/
)
returns void as
/* add two update queries inside this function */
/* 1 Updating table standards*/
'update standards
set description = _desc
where description like _WDesc and
custom_code like _custom_code;'
/*End*/
/* 2 Updating table bank*/
'update bank
set description = _desc
where description like _WDesc and
designation like _designation;'
/*End*/
language sql
这是您的一个 sql命令来更新两个表
select update_tables ('The student will demonstrate positive self esteem.',
'The student will demonstrate positive his/her self esteem.',
'qwertyuiop',
'asdfghjkl')
如果您的表(2个或更多)通过外键链接在一起,并且您想同时更新所有外键上的该外键,而不会出现“违反外键约束”错误,那么这样做是有道理的。
为此,必须使用“ ON UPDATE CASCADE
”选项创建表,或者如果已经使用以下命令填充了表,则可以对其进行更改:
ALTER TABLE child_table
DROP CONSTRAINT child_table_myField_fkey,
ADD CONSTRAINT child_table_myField_fkey FOREIGN KEY (myField, ...)
REFERENCES mother_table(myField, ...) ON UPDATE CASCADE;
从那里,您可以直接更新您的mother_table,而child_table将在后台同时更新,魔术!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.