【问题标题】:How can I add a field (for each returned record) in the query output containing the total number or the records returned by my query?如何在查询输出中添加一个字段(针对每条返回的记录),其中包含我的查询返回的总数或记录?
【发布时间】:2018-05-21 12:20:34
【问题描述】:

我对 SQL 不是很感兴趣,我在处理可以返回 0,1,>1 条记录作为输出的 MySql 查询时遇到以下问题。

我必须添加一个包含总行数的字段(每行)。因此,例如,如果我的查询返回的总数或记录总数为 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

为什么?我该如何解决?

【问题讨论】:

  • 你需要一个 GROUP BY 子句。

标签: mysql sql database group-by rdbms


【解决方案1】:

我猜语言表不会改变行数(这是合理的,因为left join),所以你可以在fromselect 中添加一个子查询:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2017-09-14
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多