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

qncylg1j  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我不太喜欢sql,在处理可以返回0,1,>1条记录作为输出的mysql查询时遇到以下问题。
我必须添加一个包含行总数的字段(每行)。例如,如果我的查询返回的记录总数是4,那么record\ u number字段hat to在所有te返回的行中都包含这个值。
我的问题是:

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

为什么?我该怎么修?

1dkrff03

1dkrff031#

我猜languages表不会更改行数(这是合理的,因为 left join ),因此您只需在 from 或者 select :

select . . .
       (select count(*) from LivestockSpecies ls2 where ls2.id = 1 or ls2.parent_livestock_species_id = 1
       ) as total_number

在mysql 8.0中,您可以使用窗口函数,因此更恰当地计算如下:

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

相关问题