我在用左联接计数行时有问题。所以我有两个表(域,聊天),我想提取每个域的聊天总数,开放聊天的数量和关闭聊天的数量。公共列是“域”。
这是我的代码:
$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个关闭)。
而不是:
结果是:
有人能帮我吗?我不明白问题在哪里..。
非常感谢!
发布于 2017-07-17 10:34:11
试试下面的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));
发布于 2017-07-17 10:31:49
相反,使用单个联接。
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
发布于 2017-07-17 10:33:54
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
https://stackoverflow.com/questions/45141814
复制相似问题