MySQL同表关联更新问题:根据id与report_id条件更新value值
UPDATE table SET value = 'Yes' WHERE (report_id = report_id AND value = 'Yes') AND id = 1 OR id = 2;
UPDATE table SET value = IF(value = 'Yes' AND report_id LIKE report_id AND id = 1, 'Yes', '') WHERE id = 2;
示例表
| id | value | report_id |
|---|---|---|
| 1 | yes | 1001 |
| 1 | no | 1002 |
| 1 | yes | 1003 |
| 2 | 1001 | |
| 2 | 1002 | |
| 3 | cat | 1001 |
| 5 | 1002 |
解决方案
方法1:自连接更新
通过自连接关联id=1和id=2的记录,直接匹配符合条件的行进行更新:
UPDATE your_table t1 JOIN your_table t2 ON t1.report_id = t2.report_id SET t2.value = 'yes' WHERE t1.id = 1 AND t1.value = 'yes' AND t2.id = 2;
注意:把
your_table替换成你实际的表名
方法2:子查询更新
先查询出所有id=1且value='yes'的report_id,再更新id=2且report_id在该列表中的记录:
UPDATE your_table SET value = 'yes' WHERE id = 2 AND report_id IN ( SELECT report_id FROM your_table WHERE id = 1 AND value = 'yes' );
原有语句问题说明
- 你写的
report_id LIKE report_id或report_id = report_id是恒成立的条件,没有起到匹配另一行记录的作用 - 所有CASE/IF判断都是基于当前行的字段,没有关联到id=1的目标行,无法实现跨行的条件判断逻辑
内容的提问来源于stack exchange,提问作者Moe
相关产品推荐
相关产品推荐

