I have one table customers which has one field 'name' with a to z names records.
I get records from a to z with asc query
SELECT * FROM `customers` ORDER BY name ASC
But how can i get 5 records which starts with all a to z alphabets with only one query?
Output:
a
a
a
a
a
b
b
b
b
b and so on to z. Thanks in advance.
Try this:
SELECT c.name
FROM (SELECT c.name, IF(@lastLetter=@lastLetter:=LEFT(c.name, 1), @cnt:=@cnt+1, @cnt:=0) letterCnt
FROM customers c, (SELECT @lastLetter:='', @cnt:=0) A
ORDER BY c.name ASC
) AS c
WHERE c.letterCnt < 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With