我正在尝试通过内部联接匹配相等日期时间(created_at)列的另一个表(表B)来更新表的列(表A,列= b_id)。
表A
+----+---------------------+-------+
| id | created_at | b_id |
+----+---------------------+-------+
| 1 | 2020-10-05 09:00:00 | NULL |
+----+---------------------+-------+
| 2 | 2020-10-05 09:05:00 | NULL |
+----+---------------------+-------+
| 3 | 2020-10-05 09:10:00 | NULL |
+----+---------------------+-------+
表B
+----+---------------------+
| id | created_at |
+----+---------------------+
| 10 | 2020-10-05 09:00:00 |
+----+---------------------+
| 11 | 2020-10-05 09:05:00 |
+----+---------------------+
| 12 | 2020-10-05 09:10:00 |
+----+---------------------+
我的以下查询有效,但我想知道是否有更有效的方法。
UPDATE A
INNER JOIN B ON A.created_at = B.created_at
SET A.b_id = B.id
WHERE A.created_at = B.created_at
答案 0 :(得分:0)
您的更新很好,尽管您可能希望将以下索引添加到B
表中:
CREATE INDEX idx_b ON B (created_at, id); -- and drop id if you're using InnoDB
这将允许MySQL使用B
值在created_at
表中进行快速查找,并假设存在的话找到相应的id
值。