要从两列中选择不同的组合,可以使用CASE语句。让我们创建一个包含一些列的表。
创建表的查询如下-
mysql> create table select_DistinctTwoColumns -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstValue char(1), -> SecondValue char(1), -> PRIMARY KEY(Id) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下-
mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('s','t'); mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('t','u'); mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','v'); mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','t');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from select_DistinctTwoColumns;
以下是输出-
+----+------------+-------------+ | Id | FirstValue | SecondValue | +----+------------+-------------+ | 1 | s | t | | 2 | t | u | | 3 | u | v | | 4 | u | t | +----+------------+-------------+ 4 rows in set (0.00 sec)
这是使用case语句从两列中选择不同组合的查询。第一列为“ FirstValue”,第二列名称为“ SecondValue”。查询如下-
mysql> SELECT distinct -> CASE -> WHEN FirstValue<SecondValue THEN FirstValue -> ELSE SecondValue -> END AS FirstColumn, -> CASE -> WHEN FirstValue > SecondValue THEN FirstValue -> ELSE SecondValue -> END AS SecondColumn -> FROM select_DistinctTwoColumns;
以下是输出:
+-------------+--------------+ | FirstColumn | SecondColumn | +-------------+--------------+ | s | t | | t | u | | u | v | +-------------+--------------+ 3 rows in set (0.00 sec)