首页 > 解决方案 > 无法使用 JOIN 更新特定记录

问题描述

我正在尝试competition使用JOIN. 的结构tables如下:

国家

id | name | iso
 5  Brazil  BR

竞争

id | country_id | name     |
 1      5          Serie A
 2      5          Serie B
 3      5          Serie C

比赛季节

id | competition_id | name  | update_at
 1         1           2019     2019-01-15 00:00:00
 2         1           2018     2019-01-15 00:00:00
 3         1           2017     2019-01-15 00:00:00
 4         2           2019     2019-01-15 00:00:00
 5         2           2018     2019-01-15 00:00:00
 6         2           2017     2019-01-15 00:00:00
 7         3           2019     2019-01-15 00:00:00
 8         3           2018     2019-01-15 00:00:00
 9         3           2017     2019-01-15 00:00:00

目标定update_atcompetition_seasonsnull所以我写了这个查询:

UPDATE country n
    JOIN competition c ON n.id = c.country_id
    JOIN competition_seasons s ON c.id = s.competition_id
    SET s.update_at = NULL
    WHERE n.name = "Brazil"

问题是查询没有更新任何东西。我做错了什么?

标签: mysqlsql

解决方案


您应该在查询中首先列出您打算更新的表。在这种情况下,我们可以颠倒连接的顺序,并competition_seasons首先列出表:

UPDATE competition_seasons s     -- target table, listed first
INNER JOIN competition c
    ON c.id = s.competition_id
INNER JOIN country n
    ON n.id = c.country_id
SET
    s.update_at = NULL
WHERE
    n.name = 'Brazil';

请注意,连接的顺序在这里应该无关紧要,假设它们都是内部连接。


推荐阅读