COALESCE和IFNULL没有返回NULL记录而不是结果

时间:2018-01-29 02:03:15

标签: mysql sql

您好我遇到的SQL语句无法正确翻译记录。我应该得到的预期结果是

Name  tag1 tag2 tag3
Brandon   0   0   0

相反,我从这4列中获取空值

这是sql Statement

SELECT 
COALESCE(merchant.merchantname, 'Brandon') AS 'Name',
IFNULL((SELECT SUM(transactionamount) from transaction where merchantid = '3' AND transactiondate = '2018-01-29' AND transactionservicetype = 'tag1'),0) AS 'TAG1',
IFNULL((SELECT SUM(transactionamount) from transaction where merchantid = '3' AND transactiondate = '2018-01-29' AND transactionservicetype = 'tag2'),0) AS 'TAG2',
IFNULL((SELECT SUM(transactionamount) from transaction where merchantid = '3' AND transactiondate = '2018-01-29' AND transactionservicetype = 'tag3'),0) AS 'TAG3' 
FROM merchant RIGHT JOIN transaction ON merchant.merchantid = transaction.merchantid
WHERE merchant.merchantid = '3' AND `transaction`.transactiondate = '2018-01-29'
ORDER BY merchant.merchantid ASC limit 1;

这是sqlfiddle的一些数据: http://sqlfiddle.com/#!9/ed1c36a/1

另外,还有另一种简化我的SQL语句的方法吗?

1 个答案:

答案 0 :(得分:2)

咦?只需使用条件聚合。我想你想要:

SELECT COALESCE(m.merchantname, 'Brandon') AS Name,
       SUM(CASE WHEN t.transactionservicetype = 'tag1' THEN t.transactionamount ELSE 0 END) as tag1,
       SUM(CASE WHEN t.transactionservicetype = 'tag2' THEN t.transactionamount ELSE 0 END) as tag2,
       SUM(CASE WHEN t.transactionservicetype = 'tag3' THEN t.transactionamount ELSE 0 END) as tag3
FROM merchant m LEFT JOIN
     transaction t
     ON m.merchantid = t.merchantid AND t.transactiondate = '2018-01-29'
WHERE m.merchantid = 3
GROUP BY m.merchantid
ORDER BY m.merchantid ASC 
LIMIT 1;

注意:

  • 使用表别名使查询更易于编写和阅读。
  • 子查询似乎没有必要。
  • 我猜merchantid是一个数字,所以请将其与数字进行比较。