我正在尝试以下代码,并希望从table2或table3获取值,status1值可能是空白(空),也可能不是空白,并且不会得到结果。
它仅显示来自table2的结果,而不是来自table3。
如果我删除“a.status1 LIKE b.status1”,那么它可以正常工作。 status1在所有表中都是空的。
SELECT a.regno,
a.status1,
Coalesce(CASE
WHEN altervalue IS NOT NULL THEN altervalue
ELSE mastervalue
end, 0) AS value1
FROM table1 a
LEFT JOIN (SELECT reg_no, total1+total2 AS altervalue
FROM table2) AS i
ON `a`.`regno` LIKE `i`.`reg_no`
LEFT JOIN (SELECT regno, total1+total2 AS mastervalue,
status1
FROM table3) AS b
ON a.status1 LIKE b.status1
答案 0 :(得分:0)
您没有使用wildchar,因此您可以使用=
代替like
SELECT
a.regno,
a.status1,
Coalesce(CASE
WHEN altervalue IS NOT NULL THEN altervalue
ELSE mastervalue
end, 0) AS value1
FROM table1 a
LEFT JOIN (SELECT reg_no, total1+total2 AS altervalue
FROM table2) AS i ON `a`.`regno` = `i`.`reg_no`
LEFT JOIN (SELECT regno, total1+total2 AS mastervalue,
status1
FROM table3) AS b ON a.status1 = b.status1
或null安全比较
SELECT
a.regno,
a.status1,
Coalesce(CASE
WHEN altervalue IS NOT NULL THEN altervalue
ELSE mastervalue
end, 0) AS value1
FROM table1 a
LEFT JOIN (SELECT reg_no, total1+total2 AS altervalue
FROM table2) AS i ON `a`.`regno` = `i`.`reg_no`
LEFT JOIN (SELECT regno, total1+total2 AS mastervalue,
status1
FROM table3) AS b ON a.status1 <=> b.status1
答案 1 :(得分:0)
首先,简化您的查询:
SELECT t1.regno, t1.status1,
COALESCE(t2.total1 + t2.total2, t3.total1 + t3.total2, 0) as value1
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.regno = t2.regno LEFT JOIN
table3 t3
ON t1.status1 = t3.status1 ;
我认为您的最终join
缺少regno
上的条件:
SELECT t1.regno, t1.status1,
COALESCE(t2.total1 + t2.total2, t3.total1 + t3.total2, 0) as value1
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.regno = t2.regno LEFT JOIN
table3 t3
ON t3.regno = t1.regno AND t3.status1 = t1.status1 ;
我不确定你的真实逻辑(你没有样本数据/结果)。您可能希望以其他顺序使用COALESCE()
:
COALESCE(t3.total1 + t3.total2, t2.total1 + t2.total2, 0) as value1