You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;

示例表

idvaluereport_id
1yes1001
1no1002
1yes1003
21001
21002
3cat1001
51002

解决方案

方法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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:50:33