来自JOIN的UPDATE COLUMN

时间:2012-07-23 21:34:13

标签: mysql sql database

我有一个名为t1的表PRIMARY KEY,我将调用ITEM_ID。 表格如下:

ITEM_ID    VALUE1
2          2500
3          3500
5          5500

我还有几个表t2t3,如下所示:

ITEM_ID    VALUE2
2          250
3          350
4          450
5          550

ITEM_ID    VALUE3
2          25
3          35
4          45
5          55
6          65

我想获得这个(我加入时只保留t1

中的行
ITEM_ID    VALUE1    VALUE2    VALUE3
2          2500      250       25
3          3500      350       35
5          5500      550       55

我知道如何使用JOINCREATE新表格执行此操作。 但是可以仅通过ALTERADDUPDATE列来实现吗?

2 个答案:

答案 0 :(得分:8)

ALTER TABLE t1 ADD VALUE2 INT, ADD VALUE3 INT;

UPDATE t1 a
JOIN   t2 b ON a.ITEM_ID = b.ITEM_ID
JOIN   t3 c ON a.ITEM_ID = c.ITEM_ID
SET    a.VALUE2 = b.VALUE2,
       a.VALUE3 = c.VALUE3;

答案 1 :(得分:2)

您可以使用可能过度的存储过程,也可以执行两个查询。如果你想先执行你的JOIN,这就是你要做的:

mysql> SELECT t1.ITEM_ID, t1.VALUE1, t2.VALUE2, t3.VALUE3 FROM t1 LEFT JOIN t2 ON t2.ITEM_ID = t1.ITEM_ID LEFT JOIN t3 ON t3.ITEM_ID = t1.ITEM_ID
    -> ;
+---------+--------+--------+--------+
| ITEM_ID | VALUE1 | VALUE2 | VALUE3 |
+---------+--------+--------+--------+
|       2 | 2500   | 250    | 25     |
|       3 | 3500   | 350    | 35     |
|       5 | 5500   | 550    | 55     |
+---------+--------+--------+--------+
3 rows in set (0.00 sec)

mysql> 

接下来,如果要创建包含这些值的新表,则可以执行以下操作:

CREATE TABLE my_temp_table (SELECT t1.ITEM_ID, t1.VALUE1, t2.VALUE2, t3.VALUE3 FROM t1 LEFT JOIN t2 ON t2.ITEM_ID = t1.ITEM_ID LEFT JOIN t3 ON t3.ITEM_ID = t1.ITEM_ID);

如果要对数据执行更新,请使用原始联接,但转换为UPDATE:

UPDATE t1 LEFT JOIN t2 ON t2.ITEM_ID = t1.ITEM_ID LEFT JOIN t3 ON t3.ITEM_ID = t1.ITEM_ID SET t1.VALUE1 = 'someValue' WHERE t1.ITEM_ID = 'someId';

以下是测试的构建:

mysql> CREATE TABLE t1 (ITEM_ID INT NOT NULL AUTO_INCREMENT, VALUE1 VARCHAR(24) NOT NULL, PRIMARY KEY (ITEM_ID));
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO t1 VALUES (2, 2500), (3, 3500), (5, 5500);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> CREATE TABLE t2 (ITEM_ID INT NOT NULL AUTO_INCREMENT, VALUE2 VARCHAR(24) NOT NULL, PRIMARY KEY (ITEM_ID));
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE t3 (ITEM_ID INT NOT NULL AUTO_INCREMENT, VALUE3 VARCHAR(24) NOT NULL, PRIMARY KEY (ITEM_ID));
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO t2 VALUES (2, 250), (3, 350), (4, 450), (5, 550);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> INSERT INTO t3 VALUES (2, 25), (3, 35), (4, 45), (5, 55), (6, 65);
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0