sql join无法正确显示

时间:2013-02-02 23:45:46

标签: php mysql join

我目前正在尝试使用左连接加入两个表:

- 门脉 -

  • id_portal(index)
  • id_venue
  • name_portal

- 访问 -

  • id_access(index)
  • id_event
  • id_portal
  • id_tickets
  • scan_access

'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

这意味着我得到以下内容:

  • Portal 1 - Null
  • Portal 2 - 40
  • Portal 3 - 33
  • Portal 4 - Null

但是当我在考虑事件(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

我明白了:

  • Portal 2 - 40
  • Portal 3 - 33

这是有意义的,因为那些是唯一具有id_event值的两行。但是如何在不丢失其他门户网站的情况下考虑这个col?另外,在返回结果时,sql中有没有办法使'null'为零? (我可以用php修复null,但想看看是否可能)

2 个答案:

答案 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