将新值添加到多行

时间:2015-11-18 10:20:18

标签: sql

我有一个存储用户的700行的现有数据库,让我们称之为users。我将有一个新列“time_code”。每个用户都有一个time_code

我将从另一个表中获取这些代码,其中每个user_name与time_code相关联,我将此表称为time code users。有没有办法将这些代码从time code users添加到users以相应的名称?

我只能用SQL吗?

3 个答案:

答案 0 :(得分:1)

{{ foo.bar }} {{ foo.baz }}

答案 1 :(得分:1)

假设你是初始数据集

CREATE TABLE USERS (USER_NO NUMBER (3), NAME VARCHAR(5));
CREATE TABLE TIME_CODE_USERS (NAME VARCHAR(5), TIME_CODE VARCHAR(3));


INSERT INTO USERS VALUES (1,'A');
INSERT INTO USERS VALUES (2,'B');
INSERT INTO USERS VALUES (3,'C');

INSERT INTO TIME_CODE_USERS VALUES ('A', 'GMT');
INSERT INTO TIME_CODE_USERS VALUES ('B', 'IST');
INSERT INTO TIME_CODE_USERS VALUES ('C', 'CET');

现在更改目标表以添加列

ALTER TABLE USERS ADD  TIME_CODE VARCHAR(3);

运行更新以填充目标

UPDATE USERS 
SET TIME_CODE = (SELECT TIME_CODE 
                 FROM TIME_CODE_USERS 
                 WHERE USERS.NAME = TIME_CODE_USERS.NAME)
WHERE EXISTS (SELECT TIME_CODE 
                 FROM TIME_CODE_USERS 
                 WHERE USERS.NAME = TIME_CODE_USERS.NAME);

检查更新

SELECT * FROM USERS;


| USER_NO | NAME | TIME_CODE |
|---------|------|-----------|
|       1 |    A |       GMT |
|       2 |    B |       IST |
|       3 |    C |       CET |

答案 2 :(得分:0)

ALTER TABLE users ADD time_code varchar(40);
UPDATE users SET users.time_code = (
    SELECT time_code FROM time_code_users
    WHERE users.username = time_code_users.username
);