SQL UPDATE如何匹配比类似SELECT更多的行?

时间:2016-01-29 14:19:33

标签: mysql sql

以下SELECT查询和UPDATE查询具有相同的FROM子句和WHERE子句。因此,我希望SELECT查询返回与UPDATE查询匹配和影响的相同行数,但如图所示,情况并非如此。

我不知道它是否相关,但是正如更新所见,我正在尝试将记录的用户名和电子邮件保存在另一列中,但正如上一个查询所示,我是不保存电子邮件,只保存用户名。

为什么会这样?

mysql> SELECT p.old_username, p.username, p.old_email, u.email
    -> FROM users u INNER JOIN people p ON p.id = u.id INNER JOIN entities e ON e.id = p.id
    -> WHERE u.id =1753671666 AND u.id !=506836355 AND e.sites_id =2846702735;
+--------------+------------+-----------+---------------------+
| old_username | username   | old_email | email               |
+--------------+------------+-----------+---------------------+
| NULL         | myusername | NULL      | myemail@example.com |
+--------------+------------+-----------+---------------------+
1 row in set (0.00 sec)

mysql>
mysql> UPDATE
    -> users u INNER JOIN people p ON p.id = u.id INNER JOIN entities e ON e.id = p.id
    -> SET p.old_username = p.username, p.username = NULL,
    -> p.old_email = u.email, u.email = NULL,
    -> e.record_status = 'inactive', e.date_modified = NOW( ), e.modified_by_id =506836355
    -> WHERE u.id =1753671666 AND u.id !=506836355 AND e.sites_id =2846702735;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql>
mysql> SELECT p.old_username, p.username, p.old_email, u.email
    -> FROM users u INNER JOIN people p ON p.id = u.id INNER JOIN entities e ON e.id = p.id
    -> WHERE u.id =1753671666 AND u.id !=506836355 AND e.sites_id =2846702735;
+--------------+----------+-----------+-------+
| old_username | username | old_email | email |
+--------------+----------+-----------+-------+
| myusername   | NULL     | NULL      | NULL  |
+--------------+----------+-----------+-------+
1 row in set (0.00 sec)

mysql>

1 个答案:

答案 0 :(得分:4)

SELECT语句报告单行是加入查询的结果。

但您正在更新 3 表:

p.old_username (and several others)
e.date_modified (and others)
u.email

因此有3个更新。