[英]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.