mysql - 如何在某些条件下从另一个表更新 MySQL 表
问题描述
我的 TABLE-A 具有以下结构:
id step1error step2error step3error
1 null {json:"string"} null
2 {json:"error1"} {json:"error2"} {json:"error3"}
和具有以下结构的表 B:
id ref(of TABLE-A) error
1 1 null
2 2 null
3 2 null
3 2 null
我尝试了以下查询,但它总是使用来自 TABLE-A 的 step1error 更新 TABLE-B。询问:
SET @exist = (select count(TABLE-B.id) from TABLE-B left join TABLE-A on TABLE-B.ref = TABLE-A.id where
TABLE-B.error = TABLE-A.step2error);
UPDATE `TABLE-B` inner join VIEW-AB on TABLE-B.ref=VIEW-AB.ref
SET TABLE-B.error =
CASE
WHEN VIEW-AB.step1error != 'null' THEN VIEW-AB.step1error
WHEN VIEW-AB.step2error != 'null' THEN VIEW-AB.step2error
ELSE VIEW-AB.step3error END
WHERE
TABLE-B.error = 'null' and
TABLE-B.id = VIEW-AB.B_ref and
@exist = 0;
VIEW-AB
create view VIEW-AB as (SELECT TABLE-B.id "B_ref", TABLE-A.step1error , TABLE-A.step2error, TABLE-A.step3error FROM `TABLE-B` left join TABLE-A on TABLE-B.ref= TABLE-A.id WHERE TABLE-B.error = 'null');
VIEW-AB 看起来像:
B_ref ref(TABLE-A) step1error step2error step3error
1 1 null {json:"string"} null
2 2 {json:"error1"} {json:"error2"} {json:"error3"}
3 2 {json:"error1"} {json:"error2"} {json:"error3"}
3 2 {json:"error1"} {json:"error2"} {json:"error3"}
我的结果:
id ref(of TABLE-A) error
1 1 {json:"string"}
2 2 {json:"error1"}
3 2 {json:"error1"}
3 2 {json:"error1"}
我需要编写一个 MySQL 查询来更新 TABLE-B(其中错误为空),如下所示:
预期结果:
id ref(of TABLE-A) error
1 1 {json:"string"}
2 2 {json:"error1"}
3 2 {json:"error2"}
3 2 {json:"error3"}
解决方案
在您的案例陈述中更新您的空检查。而不是直接'null'
使用null
。
因此mysql将'null'
其视为字符串。
使用以下查询
SET @exist = (select count(TABLE-B.id) from TABLE-B left join TABLE-A on TABLE-B.ref = TABLE-A.id where
TABLE-B.error = TABLE-A.step2error);
UPDATE `TABLE-B` inner join VIEW-AB on TABLE-B.ref=VIEW-AB.ref
SET TABLE-B.error =
CASE
WHEN VIEW-AB.step1error is not null THEN VIEW-AB.step1error
WHEN VIEW-AB.step2error is not null THEN VIEW-AB.step2error
ELSE VIEW-AB.step3error END
WHERE
TABLE-B.error = 'null' and
TABLE-B.id = VIEW-AB.B_ref and
@exist = 0;
推荐阅读
- awk - 使用 awk 比较两个不同文件中的两列
- python - 如何使用 pyqt4 创建圆形图像?
- javascript - 将 WebDriver 的浏览器实例传递给 Appium 中的 JavaScript
- django - Django 功能作为 Charfield 选择
- docker - 2 containers using the same port in Kubernetes pod
- sql-server - Windows 10 PC 无法列出 SQL Server 实例
- sql - PostgreSQL: How to return a subarray dynamically using array slices in postgresql
- java - Cloud Firestore Unit Testing Java
- javascript - Sequential programming with setTimeout in JavaScript?
- unix - 通过终端打开 Rstudio 时出错