如何在查询输出中添加一个字段(对于每个返回的记录),其中包含我的查询返回的总数或记录?

时间:2018-05-21 12:20:35

标签: mysql sql database group-by rdbms

我不是很喜欢SQL,我在MySql查询上遇到以下问题,可以返回0,1,> 1条记录作为输出。

我必须添加一个包含总行数的字段(每行)。因此,例如,如果我的查询返回的总数或记录为4,那么 record_number 字段将在所有返回的行中包含此值。

这是我的疑问:

SELECT
    LS.id                                                                           AS livestock_id,
    LS.parent_livestock_species_id                                                  AS parent_livestock_species_id,
    LS.livestock_species_name_en                                                    AS livestock_species_name_en,
    IFNULL(LSN.livestock_species_name, LS.livestock_species_name_en)                AS livestock_species_name,  
    LSN.description                                                                 AS description,
    LS.image_link                                                                   AS image_link,
    count(*)                                                                        AS record_number
FROM LivestockSpecies                                                               AS LS
LEFT JOIN LivestockSpeciesName                                                      AS LSN
      ON LSN.livestock_species_id = LS.id AND LSN.language_id = 1
WHERE
    LS.id = 1
OR
    LS.parent_livestock_species_id = 1

以某种方式执行我收到此错误消息:

#42000In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'digital_services_DB.LS.id'; this is incompatible with sql_mode=only_full_group_by

为什么呢?我该如何解决?

1 个答案:

答案 0 :(得分:1)

我猜测语言表并没有改变行数(这是合理的,因为left join),所以你可以在from或者select中添加一个子查询。 select . . . (select count(*) from LivestockSpecies ls2 where ls2.id = 1 or ls2.parent_livestock_species_id = 1 ) as total_number

select . . .
       count(*) over () as total_number

在MySQL 8.0中,您可以使用窗口函数,因此更适合计算:

constructor CreditCard in class CreditCard cannot be applied to given types;
    new CreditCard(100.0, 0.03, 2.50, 500.0);