Select distinct values from three columns and display in a single column with MySQL

MySQLMySQLi Database

For this, use UNION more than once in a single MySQL query. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int,
   -> Value3 int
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(20,null,null);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(20,null,null);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(20,null,null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(10,null,null);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(80,20,100);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(10,null,null);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     20 |   NULL |   NULL |
|     20 |   NULL |   NULL |
|     20 |   NULL |   NULL |
|     10 |   NULL |   NULL |
|     80 |     20 |    100 |
|     10 |   NULL |   NULL |
+--------+--------+--------+
6 rows in set (0.00 sec)

Following is the query to select distinct values from 3 columns into 1 −

mysql> select *from
   -> (
   -> select Value1 as AllValue from DemoTable
   -> union
   -> select Value2 as AllValue from DemoTable
   -> union
   -> select Value3 as AllValue from DemoTable
   -> ) tbl where AllValue IS NOT NULL
   -> order by AllValue;

This will produce the following output −

+----------+
| AllValue |
+----------+
|       10 |
|       20 |
|       80 |
|      100 |
+----------+
4 rows in set (0.00 sec)
raja
Published on 13-Dec-2019 10:24:03
Advertisements