1
parent_table:
ID  | FIELD1 | FIELD2
____|________|________
1   |........|......
2   |........|.....
3   |.............. 

child_table:
ID | FIELD3
___|________
1  |   18
1  |   7
2  |   ..
1  |   ..
3  |   ..
2  |   ..

Let's say I want to update these tables. This is what I need to achieve:

 UPDATE parent_table SET 
   FIELD1 = 'XXX', 
   FIELD2 = 'YYY' 
 WHERE ID = 2;

 DELETE FROM child_table 
 WHERE ID = 2;

 INSERT INTO child_table (ID, FIELD3)
   VALUES (2, 50),
   VALUES (2, 17),
   VALUES (2, 9);

note that the number of entries in the child table for each ID may vary during the update.

Is it possible to get the same result in just one query? I can't use a transaction.

maybe the first two queries are easier to merge. I tried to join the child table and set null values during the UPDATE, but I don't know how to handle the multiple rows.. Is it possible to have nested UPDATE like you have nested SELECT?

4

1 に答える 1

1

1 つのコマンドで複数のテーブルを更新できます。

UPDATE parent_table p LEFT JOIN child_table c On p.id = c.id
 SET 
   p.FIELD1 = 'XXX', 
   p.FIELD2 = 'YYY',
   c.FIELD3 = ''
 WHERE p.ID = 2;

ただし、更新と削除を同じコマンドで実行できるとは思いませんが、よくわかりません。

複数のテーブルの更新について詳しくは、こちらをご覧ください

別の (そして推奨される) アプローチは、更新時に child_table から関連するレコードを削除するトリガーを parent_table に作成することです。

于 2012-04-25T21:57:30.500 に答える