从三个列中选择不同值并在使用 MySQL 的单一列中显示
为此,在单个 MySQL 查询中多次使用 UNION。让我们先创建一个表 −
mysql> create table DemoTable -> ( -> Value1 int, -> Value2 int, -> Value3 int -> ); Query OK, 0 rows affected (0.69 sec)
使用 insert 命令在表中插入一些记录 −
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)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+--------+--------+ | 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)
以下查询可从 3 个列中选择不同值,并放入 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;
这将产生以下输出 −
+----------+ | AllValue | +----------+ | 10 | | 20 | | 80 | | 100 | +----------+ 4 rows in set (0.00 sec)
اشتہارات