0

多年来,我一直在使用简单的 MySQL 命令,并且想使用更复杂的命令。我已经接受了重写我的一些旧代码的任务,但我看不到这里发生了什么。

我正在尝试将两个表合并为一个结果,第二个表仅提供“计数”。

TABLE customers:
customerID, name, boxID
TABLE codes:
boxID, code, retrieved

我想要的正是我从 SELECT * FROM 客户那里得到的,但我想要一个额外的列,其中包含代码表中所有代码的 count(),其中 boxID 相同。

这是我当前的查询;

SELECT customers.*, count(codes.code) as codesused 
FROM customers 
INNER JOIN codes 
ON customers.boxID = codes.boxID
WHERE codes.retrieved = 1

在我添加“WHERE customers.customerID = 'x'”之前,这会导致 NULL。谁能解释为什么我不能从上面的代码中得到我想要的东西?

4

1 回答 1

5

当您将聚合函数与其他字段结合使用时,您必须使用 group by 子句。您可以像这样进行查询;

SELECT customerID, name, boxID, count(codes.code) as codesused 
FROM customers 
INNER JOIN codes ON customers.boxID = codes.boxID 
GROUP BY customerID, name, boxID, codesused
HAVING codes.retrieved = 1

并且您不能将 where 子句与 group by 一起使用,因此您必须使用 HAVING

于 2012-06-19T17:39:55.473 回答