【发布时间】:2014-08-23 13:33:34
【问题描述】:
我有两个表,我正在从中构建一些统计信息,所以我正在计算多个列和表,我的问题是当我尝试加入另一个表并将其分组到嵌套语句中时,我不断得到以下信息运行代码时出错。
General error: 2014 Cannot execute queries while other unbuffered queries are active...
这是场景:
++============================================================================++
|| CLIENTS TABLE ||
++=======+===============+==============+==============+======================++
| id | firstname | lastname | email | created_at |
+--------+---------------+--------------+--------------+-----------------------+
| 1 | JOHN | DOE | john@doe.com | 2014-08-22 20:10:30 |
+--------+---------------+--------------+--------------+-----------------------+
| 2 | JUNE | DAE | june@dae.com | 2014-07-28 18:12:08 |
+--------+---------------+--------------+--------------+-----------------------+
++============================================================================++
|| PURCHASES TABLE ||
++=======+===============+=============================+======================++
| id | client_id | transaction_status | created_at |
+--------+---------------+-----------------------------+-----------------------+
| 1 | 1 | COMPLETED | 2014-08-22 20:10:30 |
+--------+---------------+-----------------------------+-----------------------+
| 2 | 2 | INCOMPLETE | 2014-08-22 20:10:30 |
+--------+---------------+-----------------------------+-----------------------+
| 1 | 2 | COMPLETED | 2014-08-22 20:10:30 |
+--------+---------------+-----------------------------+-----------------------+
| 2 | 1 | COMPLETED | 2014-08-22 20:10:30 |
+--------+---------------+-----------------------------+-----------------------+
这是我计算的一些东西:
- 全球客户总数
- 当月客户总数
- 过去一个月的客户总数
- 最后注册的客户
- 已完成购买的客户(失败)
最后这是我失败的查询:
SELECT
( SELECT
COUNT(*)
FROM
clients
) AS
total_registered_clients,
( SELECT
COUNT(*)
FROM
clients
AND
(YEAR(created_at) = YEAR(CURRENT_DATE))
AND
(MONTH(created_at) = MONTH(CURRENT_DATE))
) AS
current_month_registered_clients,
( SELECT
COUNT(*)
FROM
clients
AND
created_at
BETWEEN
(CURRENT_DATE - INTERVAL 1 MONTH)
AND
CURRENT_DATE
) AS
last_month_registered_clients,
-- This part fails
( SELECT
COUNT(*)
FROM
clients
INNER JOIN
purchases
WHERE
purchases.client_id = clients.id
AND
purchases.transaction_status = 'completed'
GROUP BY
purchases.client_id
) AS
clients_with_purchases
编辑: 我对 var_dump 的预期结果是:
[0] =>
object(stdClass)#60 (10) {
["total_registered_clients"]=>
string(1) "2"
["current_month_registered_clients"]=>
string(1) "1"
["last_month_registered_clients"]=>
string(1) "1"
["clients_with_purchases"]=>
string(1) "2"
}
【问题讨论】:
-
由于
GROUP BY,失败的部分返回多行。当您使用SELECT作为表达式时,它必须返回单个值。你希望这能做什么? -
@Barmar 我编辑了问题以反映我的预期结果。
-
为什么
clients_with_purchases只是一个数字?你有GROUP BY purchases.client_id,所以你会得到每个客户的购买计数。 SQL 中的last_registered_client在哪里? -
@Barmar 抱歉,我已经添加了 last_registered_client 的查询,但为了不让问题这么久而删除了它,我从预期的结果编辑中删除了它,我不知道
GROUP BY返回了一个每个客户计数。 @Used_by_already 的答案很完美。感谢您的帮助@Barmar。