开发者

using a JOIN in an UPDATE in SQL

开发者 https://www.devze.com 2022-12-28 04:49 出处:网络
I\'m having trouble formulating a legal statement to double the statuses of the suppliers (s) who have shipped (sp) more than 500 units.

I'm having trouble formulating a legal statement to double the statuses of the suppliers (s) who have shipped (sp) more than 500 units. I've been trying:

update s 
set s.status = s.status * 2 
from s join sp  
    on (sp.sno = s.sno) 
group by sno 
having sum(qty) > 500;

however I'm getting this error from Mysql:

ERROR 1064 (42000): You have an error in your SQL syntax; c开发者_高级运维heck the manual that
corresponds to your MySQL server version for the right syntax to use near 
'from s join sp on (sp.sno = s.sno) group by sno having sum(qty) > 500' at line 1

Does anyone have any ideas about what is wrong with this query? Here's my schema:

create table s
  ( sno    char(5)  not null,
    sname  char(20) not null,
    status smallint,
    city   char(15),
    primary key (sno)
  );
create table p
  ( pno    char(6)  not null,
    pname  char(20) not null,
    color  char(6),
    weight smallint,
    city   char(15),
    primary key (pno)
  );
create table sp
  ( sno    char(5)  not null,
    pno    char(6)  not null,
    qty    integer  not null,
   primary key (sno, pno)
  );


Officially, ANSI SQL does not support a FROM clause in an UPDATE clause. That is a vendor specific feature. Instead you can do something like:

Update s
Set status = status * 2 
Where Exists    (
                Select 1
                From sp
                Where sp.sno = s.sno
                Group By sp.sno
                Having Sum(qty) > 500
                )


Standard SQL has MERGE which permits updates based on a join. Joins are not permitted in standard SQL UPDATEs except withing subqueries following the SET clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消