我们可以借助内部联接来更新另一个表。让我们创建两个表。
mysql> CREATE table tblFirst -> ( -> id int, -> name varchar(100) -> );
mysql> INSERT into tblFirst values(1,'John'); mysql> INSERT into tblFirst values(2,'Bob'); mysql> INSERT into tblFirst values(3,'David');
mysql> SELECT * from tblFirst;
以下是输出
+------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Bob | | 3 | David | +------+-------+ 3 rows in set (0.00 sec)
mysql> CREATE table UpdTable -> ( -> IncId int auto_increment, -> primary key(IncId), -> id int, -> name varchar(100) -> );
mysql> INSERT into UpdTable(id,name) values(1,'Taylor'); mysql> INSERT into UpdTable(id,name) values(2,'jason'); mysql> INSERT into UpdTable(id,name) values(3,'carol'); mysql> INSERT into UpdTable(id,name) values(4,'john');
mysql> SELECT * from UpdTable;
以下是输出
mysql> SELECT *from UpdTable; +-------+------+--------+ | IncId | id | name | +-------+------+--------+ | 1 | 1 | Taylor | | 2 | 2 | jason | | 3 | 3 | carol | | 4 | 4 | john | +-------+------+--------+ 4 rows in set (0.00 sec)
查看上面的输出,姓氏与第一个表记录匹配。现在,我将编写UPDATE查询-
mysql> UPDATE UpdTable -> inner join tblFirst ON (UpdTable.name = tblFirst.name) -> SET UpdTable.id = tblFirst.id; Rows matched: 1 Changed: 1 Warnings: 0
我们更新了最后一条记录,如下所示:
查询是
mysql> SELECT * from UpdTable;
以下是输出
+-------+------+--------+ | IncId | id | name | +-------+------+--------+ | 1 | 1 | Taylor | | 2 | 2 | jason | | 3 | 3 | carol | | 4 | 1 | john | +-------+------+--------+ 4 rows in set (0.00 sec)
查看示例输出。ID已更新,它是4,但现在是1。