2016-01-21 60 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'。我修复使用您的查询。谢谢:) –