通过比较和检索涉及多列的数据的SQL INSERT语句

时间:2018-08-16 03:10:16

标签: sql sql-server

+----+------------------+------------------+--------------+
| ID | EmployeeUsername |  EmployeeEmail   | ManagerEmail |
+----+------------------+------------------+--------------+
|  1 | Ron_UN           |   ron@mail.com   | pat@mail.com |
|  2 | Pat_UN           |   pat@mail.com   |              |    Pat is Ron's Manager.
|  3 | Amy_UN           |   amy@mail.com   | tom@mail.com |   
|  4 | Tom_UN           |   tom@mail.com   |              |    Tom is Amy's Manager.
+----+------------------+------------------+--------------+

我想插入一个新列ManagerUsername

+----+------------------+------------------+--------------+-----------------+
| ID | EmployeeUsername |  EmployeeEmail   | ManagerEmail | ManagerUsername | <--
+----+------------------+------------------+--------------+-----------------+
|  1 | Ron_UN           | ron@mail.com     | pat@mail.com |                 |
|  2 | Pat_UN           | pat@mail.com     |              |                 |
|  3 | Amy_UN           | amy@mail.com     | tom@mail.com |                 |
|  4 | Tom_UN           | tom@mail.com     |              |                 |
+----+------------------+------------------+--------------+-----------------+

如果ManagerUsername属于现有员工,我是否可以在ManagerEmail列中插入一条语句?

+----+------------------+------------------+--------------+-----------------+
| ID | EmployeeUsername |  EmployeeEmail   | ManagerEmail | ManagerUsername |
+----+------------------+------------------+--------------+-----------------+
|  1 | Ron_UN           | ron@mail.com     | pat@mail.com | Pat_UN <--      |
|  2 | Pat_UN           | pat@mail.com     |              |                 |
|  3 | Amy_UN           | amy@mail.com     | tom@mail.com | Tom_UN <--      |
|  4 | Tom_UN           | tom@mail.com     |              |                 |
+----+------------------+------------------+--------------+-----------------+

我目前正在计算此查询的逻辑,因此我还没有SQL语句。当我能够组建一个时,我将进行更新。

P.S。使用Microsoft SQL Server Management Studio

1 个答案:

答案 0 :(得分:4)

我们可以通过更新自我加入来做到这一点:

UPDATE a
SET ManagerUsername = b.EmployeeUsername;
FROM yourTable a
INNER JOIN yourTable b
    ON a.ManagerEmail = b.EmployeeEmail

这假设您已经在表中创建了新列ManagerUsername。如果没有,那么您必须先执行此操作,然后再运行上述更新。请注意,此更新完全符合您的预期,因为没有经理电子邮件的员工记录不会自动加入任何内容(可能是因为他们是经理记录),因此这些记录的经理用户名甚至在更新期间都不会在范围内,并且值将保持为NULL