简体   繁体   English

Mysql 用同一个表中的另一个行值更新一行

[英]Mysql update a row with another row value in same table

I have a table.我有一张桌子。 I want to update the 5th row with 10th row values from the same table.我想用同一张表中的第 10 行值更新第 5 行。 For example:例如:

SlNo   Name Quali   Exp
1        x   B.E     2
2        y   BSC     3
3        Z   B.A     1.5
4        A   MSC     2
5        B   MBA     5

Here i want to update second row with the value of 5th row.在这里,我想用第 5 行的值更新第二行。

Here is my current query:这是我当前的查询:

    UPDATE table 
      SET Name=(select Name from table where slNo='5'),
               Quali=(select Quali from  table where slNo='5'),
               Exp=(select Exp from table where slNo='5') 
      where slNo='3';

this is working fine... but if there are more than 20 columns it becomes laborious to write a query this way, because for each column I have to include another sub-query... is there any other way to write query to update the whole row with all values from the other row in the same table?这工作正常...但是如果有超过 20 列,那么以这种方式编写查询会变得很费力,因为对于每一列我必须包含另一个子查询...有没有其他方法可以编写查询来更新整行与同一表中另一行的所有值?

Use a self-join with the multiple table UPDATE syntax: 将自联接与多表UPDATE语法一起使用:

UPDATE `table` AS t1 JOIN `table` AS t2 ON t2.slNo = 5
SET    t1.Name = t2.Name, t1.Quali = t2.Quali, t1.Exp = t2.Exp
WHERE  t1.slNo = 3

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

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