我目前正在尝试使用左连接加入两个表:
- 门脉 -
- 访问 -
'access'包含每个门户网站的每个事件的多种故障单类型。我需要将这些组合起来以获得每个门户网站的scan_access列的总和,但是包含具有'null'scan_access的门户以得出'0'。为实现这一点,我使用了左连接:
SELECT portal.name_portal, SUM(access.scan_access) AS total_scan
FROM portal LEFT JOIN access ON portal.id_portal = access.id_portal
WHERE portal.id_venue = $venueId
GROUP BY portal.id_portal
ORDER BY portal.id_portal ASC
这意味着我得到以下内容:
但是当我在考虑事件(id_event)时还需要获得上述结果时我遇到了问题,因为当我使用以下内容时:
SELECT portal.name_portal, SUM(access.scan_access) AS total_scan
FROM portal LEFT JOIN access ON portal.id_portal = access.id_portal
WHERE portal.id_venue = $venueId AND access.id_event = 20
GROUP BY portal.id_portal
ORDER BY portal.id_portal ASC
我明白了:
这是有意义的,因为那些是唯一具有id_event值的两行。但是如何在不丢失其他门户网站的情况下考虑这个col?另外,在返回结果时,sql中有没有办法使'null'为零? (我可以用php修复null,但想看看是否可能)
答案 0 :(得分:2)
将access.id_event = 20
放入WHERE
条款中,即可将LEFT JOIN
变为INNER JOIN
。将access.id_event = 20
移至您的加入条件中以保留您的LEFT JOIN
。正如@echo_me所提到的,你可以使用COALESCE()
来消除你的零。我把它放在SUM()
附近,而不是在里面。
SELECT portal.name_portal, COALESCE( SUM(access.scan_access), 0 ) AS total_scan
FROM portal LEFT JOIN access ON portal.id_portal = access.id_portal AND access.id_event = 20
WHERE portal.id_venue = $venueId
GROUP BY portal.id_portal
ORDER BY portal.id_portal ASC
答案 1 :(得分:1)
将NULL转换为0使用此
COALESCE(col, 0)
在你的例子中它将是
SUM(COALESCE(access.scan_access, 0)) AS total_scan