cloying
cloying

Reputation: 365

MySQL Update - Set value in Table A with a value calculated from Table B

I have two tables:

      TABLE_A                        TABLE_B
=================          =========================
ID  |  Value | Q           TABLE_A_VALUE | Q | Name
====|========|===          ==============|===|======
 2  |  999   | 1                999      | 1 | Cat
 3  |  777   | 1                888      | 2 | Cat
                                777      | 1 | Dog
                                666      | 2 | Dog

I need to carry out an update to change TABLE_A.Q = 2 WHERE ID = 2 and in the same statement change TABLE_A.VALUE to the relevant TABLE_B.TABLE_A_VALUE performing a look-up to transform the TABLE_A_VALUE to the corresponding row with the same Name as the original value but the new Q

In other words, if I am updating the row in TABLE_A withID=2, I want to:

  1. Lookup the Value from TABLE_A in TABLE_B (999)
  2. Find the corresponding Name in TABLE_B (Cat)
  3. Find the corresponding TABLE_A_VALUE with the new Q (888)
  4. Use this value in the Update statement

.

      TABLE_A                  TABLE_A        
=================        =================    
ID  |  Value | Q         ID  |  Value | Q     
====|========|===   =>   ====|========|===    
 2  |  999   | 1          2  |  888   | 2     
 3  |  777   | 1          3  |  777   | 1     

This is the bit I am stuck on. I can:

UPDATE TABLE_A SET Q=2 WHERE ID=2

but I'm not sure about the lookup.

Any help would be gratefully received.

Upvotes: 1

Views: 84

Answers (1)

rabudde
rabudde

Reputation: 7722

The trick is the second INNER JOIN on TABLE_B to find rows with higher Q

UPDATE TABLE_A x
INNER JOIN TABLE_B y ON x.Value=y.TABLE_A_VALUE
INNER JOIN TABLE_B z ON y.Name=z.Name AND z.Q>y.Q
SET x.Q=z.Q, x.Value=z.TABLE_A_VALUE
WHERE x.ID=2

Upvotes: 1

Related Questions