2

What I need is a sql for the following I have tables

P which has columns PID, X, DX (PID is PK)
E which as columns EID, PID, X (EID is PK)

Table E has multiple entries for each PID

The statement which DOES NOT work was

update P,E set P.X=P.X+E.X, P.DX = E.X where P.PID = E.PID

I think it should be an update P set P.X = ?, P.DX = ? select( Sum(X) from E group by PID)

but I don't know how to take the output of the select and join it with P and set two values on each row;

Any help would be appreciated!

vbbartlett
  • 179
  • 2
  • 14

3 Answers3

0

You need a join in your update query, mysql supports a multi-table UPDATE as Bill karvin suggested mysql-syntax-for-join-update

UPDATE P  JOIN E ON (P.PID = E.PID)
SET P.X=P.X+E.X, P.DX = E.X 
Community
  • 1
  • 1
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
0

Try this

update P set P.X= (select sum(x) from E where e.pid=p.pid)
Thornuko
  • 287
  • 1
  • 4
0

@dianuj's answer is right syntax.

But you have one to many relationship. so, one PID has 2+ values, It is not guarranteed which value is updated.

If you dot not concern this. @dianuj's query is OK. but, Just one value is allowed for UPDATE. this question might help you. UPDATE Syntax with ORDER BY, LIMIT and Multiple Tables

Community
  • 1
  • 1
Jason Heo
  • 9,956
  • 2
  • 36
  • 64
  • Yes this is a many to one and it is important how this is updated. Found this Update P, (select PID, sum(x) as x from E group by PID) as S set p.x = p.x + s.x, p.dx = s.x where p.PID = s.PID; – vbbartlett Nov 25 '13 at 21:48