使用UPDATE查询的奇怪结果

时间:2013-03-15 12:20:32

标签: mysql sql-update

我不能为我的生活弄清楚这里发生了什么。我希望在以下查询中更新表rand_id中记录5394560的entities以匹配表rand_id中相同记录的unique_ids。相反它会更新为9?!?!?

mysql> update entities, unique_ids SET entities.rand_id = unique_ids.rand_id where entities.id=5394560;
Query OK, 1 rows affected (2.74 sec)
Rows matched: 1  Changed: 1  Warnings: 0

检查结果:

mysql> select * from entities where id=5394560;
+---------+------------------+---------+---------------------+
| id      | name             | rand_id | created_at          |
+---------+------------------+---------+---------------------+
| 5394560 | Andorra la Vella |       9 | 2013-03-15 13:58:38 |
+---------+------------------+---------+---------------------+
1 row in set (0.00 sec)

mysql> select * from unique_ids where id=5394560;
+---------+----------+
| id      | rand_id  |
+---------+----------+
| 5394560 | 26543652 |
+---------+----------+
1 row in set (0.00 sec)

我在这里错过了一些简单而愚蠢的东西吗?!?!?两个表中的两列都使用int(11),所以我认为这不是数据类型最大值的问题,但我可能错了......

1 个答案:

答案 0 :(得分:1)

你错过了两个表之间的任何连接。在理论上,实体 unique_ids 之间的关系未定义

试着找一些“WHERE entities.something = unique_ids.somethingelse”,其中some和somethingelse是每个表中列的名称。

我相信这是你的解决方案(请注意最后的“AND ...”部分):

update entities, unique_ids 
SET entities.rand_id = unique_ids.rand_id 
where entities.id=5394560 
    AND unique_ids.id=entities.id;