简体   繁体   中英

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.

Here is the SQL query:

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:

在此处输入图片说明

Now since i migrate to MySQL i need to use the same query but it seems that MySQL doesn't use 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?).

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; before the query, then replace generate_series(0, 25) as chars(letter) with ( 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

Here is the final solution:

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

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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