MySQL: Get unique values across multiple columns in alphabetical order

后端 未结 2 1717
借酒劲吻你
借酒劲吻你 2021-01-13 09:58

If my table looks like this:

id | colA   | colB | colC
===========================
1  | red    | blue | yellow
2  | orange | red  | red
3  | orange | blue |          


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 10:48

    Just do it the normal way:

    create table new_tbl(col varchar(50));
    
    
    insert into new_tbl(col)
    select cola from tbl
    union
    select colb from tbl
    union
    select colc from tbl
    

    Then sort:

    select col from new_tbl order by col
    

    Or if you don't want staging table, just do:

    select cola as col from tbl
    union
    select colb from tbl
    union
    select colc from tbl
    order by col
    

    Note: UNION automatically remove all duplicates, if you want to include duplicates, change the UNION to UNION ALL

提交回复
热议问题