1

To calculate the price of invoices (that have *invoice item*s in a separate table and linked to the invoices), I had written this query:

SELECT `i`.`id`, SUM(ii.unit_price * ii.quantity) invoice_price
FROM (`invoice` i)

JOIN `invoiceitem` ii
ON `ii`.`invoice_id` = `i`.`id`

WHERE `i`.`user_id` = '$user_id'

But it only resulted ONE row.

After research, I got that I had to have GROUP BY i.id at the end of the query. With this, the results were as expected.

From my opinion, even without GROUP BY i.id, nothing is lost and it should work well!

Please in some simple sentences tell me...

Why should I always use the additional!!! GROUP BY i.id, What is lost without it, and maybe as the most functioning question, How should I remember that I have lost the additional GROUP BY?!

4

2 回答 2

4

您必须包括 group by,因为总和中有很多 ID。如果你没有指定它,那么 MySQL 只会选择第一个,然后对整个结果集求和。GroupBy 告诉 MySQL 为每个 Grouped By Entity 求和(或一般聚合)。

于 2013-06-27T19:46:46.667 回答
3

为什么我要一直使用GROUP BY

SUM()和其他的是聚合函数。它们的本质要求它们与GROUP BY.

没有它会失去什么?

从文档中:

如果在不包含 GROUP BY 子句的语句中使用分组函数,则相当于对所有行进行分组。

最后,没有什么要记住的,因为这些是GROUP BY聚合函数。GROUP BY当结果包括整个结果集(错误地)而不是分组子集时,您会很快从结果中看出您忘记了。

于 2013-06-27T19:46:24.757 回答