2016-01-21 77 views
0

我有table1tbl_cat。我想更新的x值,其中animalcat從另一列更新列條件爲

table1 
id id_animal animal x 
2   1  cat  3 
3   2  cat  5 
4   1  dog  7 
5   2  dog  8 
6   3  dog  9 

tbl_cat 
id x 
1 10 
2 30 

結果後市展望:

table1 
id id_animal animal x 
2   1  cat  10 
3   2  cat  30 
4   1  dog  7 
5   2  dog  8 
6   3  dog  9 

我使用此查詢,但它不工作:

update table1 
set table1.x = tbl_cat.x 
from table1 inner join tbl_cat 
on (table1.id_animal=tbl_cat.id) 
where table1.animal='cat' 

回答

1

Postgres里正確的語法是:

update table1 
    set table1.x = tbl_cat.x 
    from tbl_cat 
    where table1.id_animal = tbl_cat.id and 
      table1.animal = 'cat'; 

由於某些不可理解的原因,在更新子句(MySQL,SQL Server和Postgres)中支持join的三個主要數據庫都有不同的語法。您的語法是SQL Server語法。

+1

「*由於某些莫名其妙的原因*」 - 我猜這是因爲SQL標準沒有定義任何UPDATE連接。 –

+0

我用你的方式。但我得到一個錯誤:錯誤:表名「table1」指定不止一次 –

+1

我得到我的錯。我寫了'來自table1'。我修復使用您的查詢。謝謝:) –