使用LEFT JOIN计算行数

时间:2017-07-17 10:28:59

标签: php mysql

我使用LEFT JOIN计算行数有问题。 所以我有2个表(域名,聊天),我想提取每个域,聊天总数,打开聊天数和关闭聊天数。公共列是"域"

这是我的代码:

$getDomains = $DB->query("
SELECT 
dom.id as domainID, dom.name as domainName, dom.domain as url, dom.gmt, dom.opening_hours, 
COUNT(t1.id) as chats, 
COUNT(t2.id) as opened_chats, 
COUNT(t3.id) as closed_chats

FROM domains dom

LEFT OUTER JOIN chat t1 ON t1.domain=dom.domain
LEFT OUTER JOIN chat t2 ON t2.domain=dom.domain AND t2.status=1
LEFT OUTER JOIN chat t3 ON t3.domain=dom.domain AND t3.status=3

WHERE dom.account_id = ".$userInfo['account_id']." GROUP BY dom.domain") or die (mysqli_error($DB));

在聊天栏中,我有6个聊天(3个打开,3个关闭)。

而不是:

  • 所有聊天记录:6
  • 打开聊天记录:3
  • 封闭式聊天记录:3

结果是:

  • 所有聊天记录:54
  • 打开聊天记录:54
  • 关闭聊天记录:54

任何人都可以帮帮我吗?我无法理解问题出在哪里......

非常感谢!

3 个答案:

答案 0 :(得分:0)

而是使用单个联接

SELECT dom.*, 
       COUNT(t.id) as chats, 
       sum(t.status=1) as opened_chats, 
       sum(t.status=3) as closed_chats
FROM domains dom
LEFT OUTER JOIN chat t ON t.domain=dom.domain

答案 1 :(得分:0)

SELECT
  dom....,
  COUNT(*) as chats,
  SUM(chat.status=1) as opened_chats,
  SUM(chat.status=3) as closed_chats
FROM
  domains dom
LEFT JOIN
  chat ON chat.domain = dom.domain
WHERE dom.account_id = ? 
GROUP BY dom.domain

答案 2 :(得分:0)

尝试以下查询LEFT OUTER JOIN

$getDomains = $DB->query("
    SELECT 
    dom.id as domainID, dom.name as domainName, dom.domain as url, dom.gmt, dom.opening_hours, 
    (select count(t1.id) from chat as t1 where t1.domain=dom.domain) as chats,
    (select count(t2.id) from chat as t1 where t2.domain=dom.domain AND t2.status=1) as opened_chats,
    (select count(t3.id) from chat as t1 where t3.domain=dom.domain AND t3.status=3) as closed_chats

    FROM domains dom

    WHERE dom.account_id = ".$userInfo['account_id']." GROUP BY dom.domain") or die (mysqli_error($DB));