Select distinct values from multiple columns in same table

前端 未结 4 1606
[愿得一人]
[愿得一人] 2021-01-01 10:54

I am trying to construct a single SQL statement that returns unique, non-null values from multiple columns all located in the same table.

 SELECT distinct tb         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 11:28

    Union is applied wherever the row data required is similar in terms of type, values etc. It doesnt matter you have column in the same table or the other to retrieve from as the results would remain the same ( in one of the above answers already mentioned though).

    As you didn't wanted duplicates theres no point using UNION ALL and use of distinct is simply unnecessary as union gives distinct data

    Can create a view would be best choice as view is a virtual representation of the table. Modifications could be then done neatly on that view created

    Create VIEW getData AS 
    (
      SELECT distinct tbl_data.code_1 
        FROM tbl_data
        WHERE tbl_data.code_1 is not null
      UNION
      SELECT tbl_data.code_2 
        FROM tbl_data
        WHERE tbl_data.code_2 is not null
    );
    

提交回复
热议问题