Mysql更新值

时间:2011-04-16 09:57:41

标签: mysql

我在数据库中使用了两个表。第一个表格如下:

   id    |   msg_id   |     user   |   date   
-------------------------------------------------
   01    |    122     |    user 1  | 2011-04-01
   02    |    453     |    user 2  | 2011-04-03
   03    |    124     |    user 3  | 2011-04-05

第二个表看起来像这样:

       id    |   msg_id   |     status   | 
   ----------------------------------------
       01    |      0     |       1      | 
       02    |      0     |       1      | 
       03    |     124    |       1      | 

我想根据第一个表中的msg_id记录更新第二个表中“0”值(“msg_id”列)的所有行。 是否可以使用单个查询来完成?

结果如下:

       id    |   msg_id   |     status   | 
   ----------------------------------------
       01    |    122     |       1      | 
       02    |    453     |       1      | 
       03    |    124     |       1      | 

5 个答案:

答案 0 :(得分:1)

UPDATE table1 AS t1, table2 AS t2
SET t2.msg_id=t1.msg_id
WHERE t1.id = t2.id and t2.msg_id = 0;

答案 1 :(得分:0)

UPDATE secondTable 
SET msg_id = (SELECT msg_id FROM firstTable WHERE firstTable.msg_id = secondTable.msg_id)
WHERE msg_id = 0;

答案 2 :(得分:0)

UPDATE  table2 t2
JOIN    table1 t1
ON      t2.id = t2.id
SET     t2.msg_id = t1.msg_id
WHERE   t2.msg_id = 0

答案 3 :(得分:0)

TRY

UPDATE table2 t2  SET msg_id = (SELECT msg_id 
  FROM table1 t1 where t2.id = t1.id AND t2.msg_id=0)

答案 4 :(得分:0)

UPDATE secondTable as st , firstTable as ft set st.msg_id = ft. msg_id WHERE ft.id = st.id
and st.msg_id = 0;