MySQL 更新有异常的查询

MySQL UPDATE query with exceptions

我有两个 table:chapterupdates

我有一个更新查询,用于将成员 ID 从 updates table 设置到 chapter table。我试图找到一种语法解决方案的问题是我需要使用一个查询,但如果更新值为 '0',则让它不更新(跳过)该值。提交更新时(等待更新处理),并不是所有的 ID 都被更改,那些没有被保存到我的 updates table 中的 '0' 而有效的更改是七位数字整数。应用更新时会出现问题,当该字段实际上应该保留其现有值时,任何现有 ID 都会被 '0' 覆盖。我当前查询的示例是:

UPDATE chapter
SET chapter.election_date = updates.election_date,
 chapter.president = updates.president_id,
 chapter.vice_president = updates.vice_president_id,
 chapter.secretary = updates.secretary_id,
WHERE
    updates.chapter_id = chapter.id
AND updates.installation_date < CURRENT_DATE ()

基于这个例子,我试图找到一种方法让 chapter.presidentupdates.president_id = '0'

时不更新

如果可行,我们将不胜感激任何帮助或指导。

只需将此条件添加到 join 子句中:

UPDATE chapter
JOIN   updates ON updates.chapter_id = chapter.id AND 
                  updates.president_id != '0'
SET    chapter.election_date = updates.election_date,
       chapter.president = updates.president_id,
       chapter.vice_president = updates.vice_president_id,
       chapter.secretary = updates.secretary_id,
WHERE  updates.installation_date < CURRENT_DATE ()

如果 updates.president_id=0,下面的查询将不会更新 chapter.president,但会更新所有其他字段。

UPDATE chapter, updates
SET chapter.election_date = updates.election_date,
 chapter.president = if(updates.president_id<>0,updates.president_id,chapter.president)
 chapter.vice_president = updates.vice_president_id,
 chapter.secretary = updates.secretary_id,
WHERE
    updates.chapter_id = chapter.id
AND updates.installation_date < CURRENT_DATE()