为表中的每个ID和ID本身获取COUNT-MySQL

时间:2019-08-23 08:17:52

标签: mysql

我想知道invoiceID在该发票所具有的invoiceLines中出现的频率。例如这样

+++++++++++++++++++++++++++++++++
+ invoiceID+ COUNT(invoiceLines)+
+++++++++++++++++++++++++++++++++
+ 1        + 10                 +
+++++++++++++++++++++++++++++++++
+ 2        + 17                 +
+++++++++++++++++++++++++++++++++
+ 3        + 5                  +
+++++++++++++++++++++++++++++++++

我当前的查询如下:

select DISTINCT invoice.invoiceID, COUNT(invoiceLine.invoiceLineID) 
from invoice join invoiceLine on invoiceLine.fk_invoiceID = 
invoice.invoiceID;

尽管这不起作用,因为我选择的是非聚合值和聚合值。因此,错误消息:

In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'wms_new.invoice.invoiceID'; this is incompatible with sql_mode=only_full_group_by

有人知道如何在不禁用“ sql_mode = only_fill_group_by”的情况下完成类似的事情

1 个答案:

答案 0 :(得分:3)

实际上可以完全通过发票行表回答此要求。您不需要联接即可开具发票:

select fk_invoiceID, COUNT(*) 
from invoiceLine 
group by fk_invoiceID

在当前的MySQL模式下,选择列表中不是聚合函数的每一列(计数,最小值,最大值,和,平均值等)也必须出现在分组依据中

使用DISTINCT的情况非常狭窄;设法避免使用它。分组查询中不需要它,因为从本质上讲,它们会产生输出,其中行是一组唯一的值