MySQL: Get unique values across multiple columns in alphabetical order

后端 未结 2 1701
借酒劲吻你
借酒劲吻你 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条回答
  • 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

    0 讨论(0)
  • 2021-01-13 10:57
    (SELECT DISTINCT colA AS color FROM table) UNION
    (SELECT DISTINCT colB AS color FROM table) UNION
    (SELECT DISTINCT colC AS color FROM table)
    ORDER BY color
    
    0 讨论(0)
提交回复
热议问题