此代码对a和b进行操作,并检查结果是否等于c。 如果是,只需打印此行。我的问题是如何更改此代码以显示 结果(a / b)= 0时的行。
SELECT id, a, b, operation, c
FROM expressions
where
case
when operation LIKE '+' AND (a + b = c) then c
when operation LIKE '-' AND (a - b = c) then c
when operation like '/' AND (a / b = c) then c
when operation like '*' AND (a * b = c) then c
ELSE FALSE END;
输出:
id a b operation c
1 2 3 + 5
4 4 7 * 28
11 0 1 / 0
14 239 0 * 0
15 18 18 - 0
1,2行可以打印。应该打印3,4,5行,但它们不是! 当a / b = 0时,sql查询中的第二个条件为false - 不打印行,例如0/1 = 0.它为0,应该打印。与1/0相反,不应该打印。 我的解决方案是将(a / b = c)转换为无符号,但它不起作用?
答案 0 :(得分:2)
您不应混用boolean
和int
等类型,因为会发生隐式转换。
使用显式值代替TRUE/FALSE
(0
被视为FALSE
)。
SELECT id, a, b, operation, c
FROM expressions
where
case
when operation LIKE '+' AND (a + b = c) then 1
when operation LIKE '-' AND (a - b = c) then 1
when operation like '/' AND (a / b = c) then 1
when operation like '*' AND (a * b = c) then 1
ELSE 0 END = 1;
或者:
SELECT id, a, b, operation, c
FROM expressions
where
case
when operation LIKE '+' AND (a + b = c) then TRUE
when operation LIKE '-' AND (a - b = c) then TRUE
when operation like '/' AND (a / b = c) then TRUE
when operation like '*' AND (a * b = c) then TRUE
ELSE FALSE END;
答案 1 :(得分:1)
正如已经指出的那样,问题是0
被视为错误。
我会将逻辑简化为:
SELECT id, a, b, operation, c
FROM expressions
WHERE (operation LIKE '+' AND (a + b = c) ) OR
(operation LIKE '-' AND (a - b = c) ) OR
(operation LIKE '/' AND (a / b = c) ) OR
(operation LIKE '*' AND (a * b = c) );
我不认为CASE
使代码更容易理解。
如果您担心被零除,请使用nullif()
:
(operation LIKE '/' AND (a / nullif(b, 0) = c) ) OR