简体   繁体   English

MySQL更新-在表A中设置值,并使用从表B计算得出的值

[英]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 我需要进行更新以更改TABLE_A.Q = 2 WHERE ID = 2并在同TABLE_A.VALUE语句TABLE_A.VALUE更改为相关的TABLE_B.TABLE_A_VALUE执行查找以将TABLE_A_VALUE转换为具有相同Name的对应行作为原始值,但是新的Q

In other words, if I am updating the row in TABLE_A with ID=2 , I want to: 换句话说,如果我要更新TABLE_AID=2的行,我想:

  1. Lookup the Value from TABLE_A in TABLE_B (999) TABLE_BTABLE_A查找Value (999)
  2. Find the corresponding Name in TABLE_B (Cat) TABLE_B找到相应的Name (猫)
  3. Find the corresponding TABLE_A_VALUE with the new Q (888) 用新的Q查找对应的TABLE_A_VALUE (888)
  4. Use this value in the Update statement Update语句中使用此值

.

      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. 任何帮助将不胜感激。

The trick is the second INNER JOIN on TABLE_B to find rows with higher Q 诀窍是在TABLE_B上第二个INNER JOIN查找具有更高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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM