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

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

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


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

这是我当前的查询;

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


直到我添加“ WHERE customer.customerID ='x'”,结果为NULL。谁能解释为什么我不能从上面的代码中得到想要的东西?

最佳答案

当您将聚合函数与其他字段组合时,必须使用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

关于php - 在指定WHERE之前没有MySQL结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11106262/

10-11 07:04