mysql 基于多个条件的列的和返回null,为什么?

uidvcgyl  于 11个月前  发布在  Mysql
关注(0)|答案(3)|浏览(89)

我有一个费用表,其中多个费用可以绑定到一个ID,但这些费用中的每一个都可以有一个特定的类型。


的数据
我可以得到一个类型的总和。

SELECT 
    SUM(expense) AS total 
FROM expenses
WHERE id = 1 AND type = 'cleaning';

字符串
但是我想得到一个有两种类型的费用的总和,所以我试着

SELECT
    SUM(expense) AS total 
FROM expenses 
WHERE id = 1 
AND type = 'cleaning' 
AND type = 'painting';


我希望它返回3000,但它返回NULL。
为什么AND运算符在这种情况下不起作用?

nzkunb0c

nzkunb0c1#

为每行计算where子句。不存在以下行:

type = 'cleaning' AND type = 'painting'

字符串
因为sum看不到行,所以它返回null

rjee0c15

rjee0c152#

SELECT
    SUM(expense) AS total 
FROM expenses 
WHERE id = 1 
AND type = 'cleaning' 
AND type = 'painting';

字符串
查询表明您要对SUM同时等于cleaningpainting的所有记录的expense进行SUM
由于Type要么不匹配这两个值中的任何一个,要么只匹配其中一个,而您的条件要求它匹配这两个值,因此没有记录匹配该条件,因此SUM计算空集的和。
试试看:

SELECT
    SUM(expense) AS total 
FROM expenses 
WHERE id = 1 
AND type IN ('cleaning', 'painting');


SELECT
    SUM(CASE WHEN Type = 'cleaning' THEN expense ELSE 0 END) AS total_cleaning,
    SUM(CASE WHEN Type = 'painting' THEN expense ELSE 0 END) AS total_painting
FROM expenses 
WHERE id = 1;


而不是.

zed5wv10

zed5wv103#

这是因为根据查询,您正在搜索一个既有油漆又有清洁的类型。
你可以尝试使用OR来获得油漆和清洁的总和。

SELECT SUM(expense) AS total FROM expenses WHERE id = 1 AND (type = 'cleaning' OR type = 'painting');

字符串

相关问题