简体   繁体   English

如何使用MySQL中等效的generate_series()来计数项目?

[英]How to count items using generate_series() equivalent in MySQL?

i have a list of users in my Postgresql db and i want to count how many users there are for every letter. 我在Postgresql数据库中有一个用户列表,我想计算每个字母有多少个用户。

Here is the SQL query: 这是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

(thanks to this answer ) (由于这个答案

Here is the result in PHPPGAdmin: 这是PHPPGAdmin中的结果:

在此处输入图片说明

Now since i migrate to MySQL i need to use the same query but it seems that MySQL doesn't use generate_series(). 现在,由于我迁移到MySQL,因此我需要使用相同的查询,但似乎MySQL不使用generate_series()。 So, how to get the same result? 那么,如何获得相同的结果呢?

So lets assume you have some table with at least 26 records in it (maybe information_schema.columns perhaps?). 因此,假设您有一个至少包含26条记录的表(也许是information_schema.columns ?)。

The following will generate all uppercase alphabetical letters: 以下将生成所有大写字母:

SET @c := 64;

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

To embed the above into your original query, put the SET @c := 64; 要将以上内容嵌入到原始查询中,请SET @c := 64; before the query, then replace generate_series(0, 25) as chars(letter) with ( SELECT CAST ... LIMIT 26 ) chars . 在查询之前,然后将generate_series(0, 25) as chars(letter)替换为( SELECT CAST ... LIMIT 26 ) chars Be sure to include the parentheses as it will make the query into a subquery. 确保包括括号,因为它将使查询成为子查询。

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

Here is the final solution: 这是最终的解决方案:

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

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM