SQL Query将数据从2个表更新为另一个表

时间:2013-04-05 14:35:45

标签: mysql sql sql-update

我有一个table_a,我想用其他2个表的数据更新。

table_a
+----+---------+------------+-------+
| id |  user   |    date    | valid | 
+----+---------+------------+-------+
| 10 | Bob     |            |       |
| 11 | Joe     |            |       |
| 12 | Joe     |            |       |
| 13 | Pete    |            |       |
| 14 | Bob     |            |       | 
+----+---------+------------+-------+

日期来自table_b,其中table_b.rel_id = table_a.id

table_b
+----+----------+----------+
| id |  rel_id  |  date    | 
+----+----------+----------+
| 30 |    8     | 10/10/11 |
| 31 |    9     | 10/10/11 |
| 32 |   10     | 10/10/11 |
| 33 |   11     | 10/10/11 |
| 34 |   12     | 10/10/11 |
| 35 |   13     | 10/10/11 |
| 36 |   14     | 10/10/11 |        
+----+----------+----------+

并且有效来自table_c,其中table_c.rel_id = table_a.id

table_c
+----+----------+----------+
| id |  rel_id  |  valid   | 
+----+----------+----------+
| 40 |   10     |   yes    |
| 41 |   11     |   no     |
| 42 |   12     |   yes    |
| 43 |   13     |   no     |
| 44 |   14     |   yes    |
| 45 |   15     |   no     |
| 46 |   16     |   yes    |        
+----+----------+----------+

如何使用SQL查询完成此操作?

1 个答案:

答案 0 :(得分:4)

您可以使用INNER JOIN简单地加入表格。

UPDATE  table_a a
        INNER JOIN table_b b
            ON a.id = b.rel_id
        INNER JOIN table_c c
            ON a.id = c.rel_id
SET     a.date = b.date,
        a.valid = c.valid