Group PHP results on first letter of name

后端 未结 6 1430
粉色の甜心
粉色の甜心 2020-12-10 17:25

I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the last name and display the

6条回答
  •  不知归路
    2020-12-10 17:59

    Yes you can achive this using MySql itself

    In my case brand_name going to be list out as you expected.

    Example :

    SELECT id, upper(SUBSTR(brand_name, 1, 1))  AS alpha FROM products WHERE  brand_name != ''  group by alpha
    UNION
    SELECT id, upper(SUBSTR(brand_name, 1, 1))  AS alpha FROM products WHERE  brand_name != '' order by brand_name COLLATE NOCASE
    

    Result :

        A
        A Card
        A Cef
        A Cef O
        B
        Bacticef Tab
        Bacticin
        Bactidrox
        Bactidrox Kid
        ........
    

    Hope it will help someone.

提交回复
热议问题