2

テーブルのフィールドを更新する必要があります。次のクエリを使用しています。助けて、どっちが正しい?

update table1
set col1=<value>,col2=<value>....
from table1 t,table2 s
where t.id=s.num
  and s.code='abc';

また

update table1
set col1=<value>,col2=<value>....
where table1.id=table2.num
  and table2.code='abc';

どちらが正しいですか?それとも両方とも間違っていますか?何かいい方法を教えてください...

4

6 に答える 6

8

どちらも正しくありません。フラグメントから何をしようとしているのかは明確ではありませんが、あるテーブルを別のテーブルの値で更新する構文は次のようになります。

update table1
set (col1, col2) =
( select col1, col2
  from   table2
  where  table2.num = table1.id
  and    table2.code = 'abc'
)
where table1.id in (select num from table2);

最後の WHERE 句は、一致しないすべての table1 行が null で更新されるのを防ぐためのものです。

クエリでtable1 が「キーを保持」している場合に機能する別の方法は次のとおりです。

update
( select table1.id, table1.col1, table1.col2
  ,      table2.col1 as new_col1, table2.col as new_col2
  from   table1
         join table2 on table2.num = table1.id
)
set col1 = new_col1, col2 = new_col2;
于 2009-02-17T09:55:05.970 に答える
3

最後の発言に基づいて、テーブル table1 をデータベース テーブルにない固定値で更新する必要があります。ただし、テーブル 2 の特定の行と一致するテーブル 1 の行のみです。その場合、次のステートメントを使用できます。

update table1 t1
set t1.col1='value',
t1.col2='value2',
t1.col3='value3'
where exists ( select ''
               from table2 s 
               where  t1.id=s.num 
               and s.code='abc'
);
于 2009-02-17T15:19:50.493 に答える
1

次のクエリを使用しました。

update (select col1 from table1 t inner join table2 s
on t.id=s.num where s.code='abc') t1
set t1.col1='value';

それはうまくいきました..

しかし、複数の列を更新するために使用すると、エラーが発生しました:

右括弧がありません。

手伝ってくれる...

update (select col1,col2,col3 from table1 t inner join table2 s
on t.id=s.num where s.code='abc') t1
set t1.col1='value',t1.col2='value2',t1.col3='value3';
于 2009-02-17T10:38:01.997 に答える