2017-07-17 67 views
0

我使用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

任何CAND帮助我吗?我不明白问题在哪里...

非常感谢!

回答

0

尝试以下查询insted的的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)); 
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 
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 
+0

感谢的人!它的工作:) –

+0

如果我有更多的行仍然存在问题...我修复它,谢谢 –