在 MySQL 中从两列中选择独特的组合?
要从两列中选择独特的组合,可以使用 CASE 语句。让我们创建一个带有一些列的表格。
用于创建表格的查询如下:
mysql> create table select_DistinctTwoColumns -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstValue char(1), -> SecondValue char(1), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.57 sec)
现在,可以使用 insert 命令在表格中插入一些记录。查询如下:
mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('s','t'); Query OK, 1 row affected (0.12 sec) mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('t','u'); Query OK, 1 row affected (0.24 sec) mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','v'); Query OK, 1 row affected (0.12 sec) mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','t'); Query OK, 1 row affected (0.16 sec)
使用 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)
广告