添加where子句时,我陷入了查询困境。不出所料,我没有结果,所以SUM没有任何工作。当没有行与where语句匹配时,我尝试为countSend和countPending返回默认值0。
SELECT
SUM(CASE WHEN orders.status = "send" THEN 1 ELSE 0 END) countSend,
SUM(CASE WHEN orders.status = "pending" THEN 1 ELSE 0 END) countPending
FROM orders
LEFT OUTER JOIN order_posts AS op ON op.order_id = orders.id
LEFT OUTER JOIN posts AS p ON p.id = op.post_id
WHERE (orders.id LIKE "%Shop 3%") OR (p.title LIKE "%Shop 3%")
GROUP BY orders.id
LIMIT 1
答案 0 :(得分:1)
您可以使用coalesce()
,当该值不是NULL
或第二个表达式的值时,它将返回第一个表达式求值的值。 (这也适用于两个以上的表达式,但在您的情况下只有两个)。
SELECT coalesce(sum(CASE
WHEN orders.status = "send" THEN
1
ELSE
0
END),
0) countSend,
coalesce(sum(CASE
WHEN orders.status = "pending" THEN
1
ELSE
0
END),
0) countPending
...
答案 1 :(得分:1)
我不太确定您要完成什么,但是GROUP BY
可能不是必需的。以下内容将始终返回一行:
SELECT SUM(o.status = 'send') as countSend,
SUM(o.status = 'pending') as countPending
FROM orders o LEFT OUTER JOIN
order_posts op
ON op.order_id = o.id LEFT OUTER JOIN
posts p
ON p.id = op.post_id
WHERE (o.id LIKE '%Shop 3%') OR (p.title LIKE '%Shop 3%');
如果WHERE
子句将所有内容过滤掉,您仍将获得一行,带有NULL
值。使用COALESCE()
返回0
:
SELECT COALESCE(SUM(o.status = 'send'), 0) as countSend,
COALESCE(SUM(o.status = 'pending'), 0) as countPending