【问题标题】:How to count items using generate_series() equivalent in MySQL?如何在 MySQL 中使用 generate_series() 等效项来计算项目?
【发布时间】:2015-07-21 17:07:00
【问题描述】:

我的 Postgresql 数据库中有一个用户列表,我想计算每个字母有多少用户。

这是 SQL 查询:

select chr(chars.letter + ascii('A')) as letter,
       count(m.nome)
from generate_series(0, 25) as chars(letter)
left join merchant m on ascii(left(m.nome, 1)) = chars.letter + ascii('A')
group by letter
order by letter asc

(感谢this answer

这是 PHPPGAdmin 中的结果:

现在,由于我迁移到 MySQL,我需要使用相同的查询,但似乎 MySQL 不使用 generate_series()。那么,如何得到同样的结果呢?

【问题讨论】:

    标签: mysql sql postgresql count alphabetical


    【解决方案1】:

    假设您有 一些 表,其中至少有 26 条记录(也许是 information_schema.columns?)。

    以下将生成所有大写字母:

    SET @c := 64;
    
    SELECT CAST(CHAR(@c := @c + 1) AS CHAR(1)) AS letter
    FROM table_with_at_least_26_rows
    LIMIT 26
    ;
    

    要将以上内容嵌入到您的原始查询中,请将SET @c := 64; 放在查询之前,然后将generate_series(0, 25) as chars(letter) 替换为( SELECT CAST ... LIMIT 26 ) chars。请务必包含括号,因为它会将查询变成子查询。

    查询的 SQL Fiddle:http://sqlfiddle.com/#!9/6efac/8

    【讨论】:

    • 嗯...事实是我无法嵌入它:(
    • @smartmouse - 不知道怎么做,还是不允许?
    • 我不知道如何,我尝试了几种方法,但都没有奏效。
    • @smartmouse - 更新答案
    • 此时,制作一个包含每个字母的表格可能会更快/更容易。整个过程只需 60 秒,您再也不用担心了。
    【解决方案2】:

    这是最终的解决方案:

    SELECT
       LEFT(name, 1) AS first_letter,
       COUNT(*) AS total
    FROM users
    GROUP BY first_letter
    

    Source

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 2018-02-08
      • 1970-01-01
      • 2021-07-15
      • 2019-05-23
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多