简体   繁体   中英

Mysql - How to search for 26 records that each begins with the letter of the alphabet?

Basically I'm trying to create a query that can retrieve 26 words from a table based on the letters of the English alphabet (26 letters). So "Apple, Banana, Coconut..." etc.

I've been using 'like a%', so:

SELECT * from 'word' WHERE word_name like 'a%' limit 1 - which gives me a word that begins with 'a'.

SELECT * from 'word' WHERE word_name like 'a%' or word_name like 'b%' - which gives me multiple words beginning with 'a' or 'b'.

SELECT * FROM word WHERE word_name BETWEEN 'a' AND 'e' - list all words that begins with ae. Seems more powerful. From here, I need to know how to limit the query to finding just one word per letter and 26 words in total, I've tried the following:

SELECT DISTINCT word_name FROM `word` WHERE word_name BETWEEN 'a' AND 'z' limit 26;

SELECT DISTINCT word_name FROM `word` WHERE word_name like [a-z]% limit 26;

I feel like I'm getting the right idea but neither of these are working for me. I'm familiar with php so I could go the really long route and create a query for every letter and put that into an array, but is there already a mysql solution for this?

如何group by每个单词的第一个字母group by

SELECT word_name FROM `word` GROUP BY SUBSTRING(word_name,0,1)

this should work

SELECT DISTINCT LEFT(word_name, 1) as letter, word_name
FROM word
 GROUP BY (letter)
 ORDER BY letter

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