Computer >> Máy Tính >  >> Lập trình >> MySQL

MYSQL chọn giá trị DISTINCT từ hai cột?

Để chọn các giá trị khác nhau trong hai cột, bạn có thể sử dụng hàm ít nhất () và lớn nhất () từ MySQL.

Hãy để chúng tôi tạo một bảng có hai cột -

mysql> create table SelectDistinctTwoColumns
   −> (
   −> StudentId int,
   −> EmployeeId int
   −> );
Query OK, 0 rows affected (0.60 sec)

Bây giờ bạn có thể chèn các bản ghi trong bảng. Truy vấn để chèn bản ghi như sau -

mysql> insert into SelectDistinctTwoColumns values(100,101);
Query OK, 1 row affected (0.39 sec)

mysql> insert into SelectDistinctTwoColumns values(102,103);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SelectDistinctTwoColumns values(104,105);
Query OK, 1 row affected (0.18 sec)

mysql> insert into SelectDistinctTwoColumns values(100,101);
Query OK, 1 row affected (0.14 sec)

mysql> insert into SelectDistinctTwoColumns values(102,103);
Query OK, 1 row affected (0.12 sec)

mysql> insert into SelectDistinctTwoColumns values(106,107);
Query OK, 1 row affected (0.36 sec)

mysql> insert into SelectDistinctTwoColumns values(104,105);
Query OK, 1 row affected (0.17 sec)

mysql> insert into SelectDistinctTwoColumns values(105,104);
Query OK, 1 row affected (0.35 sec)

Hiển thị tất cả các bản ghi từ bảng với sự trợ giúp của câu lệnh select. Truy vấn như sau -

mysql> select *from SelectDistinctTwoColumns;

Sau đây là kết quả -

+-----------+------------+
| StudentId | EmployeeId |
+-----------+------------+
| 100       | 101        |
| 102       | 103        |
| 104       | 105        |
| 100       | 101        |
| 102       | 103        |
| 106       | 107        |
| 104       | 105        |
| 105       | 104        |
+-----------+------------+
8 rows in set (0.00 sec)

Nhìn vào đầu ra ở trên. Có thể thấy một số giá trị trùng lặp trong cả hai cột. Đây là truy vấn chọn giá trị khác biệt từ các cột -

mysql> select distinct least(StudentId, EmployeeId) as FirstColumn,
   −> greatest(StudentId, EmployeeId) as SecondColumn from SelectDistinctTwoColumns;

Sau đây là kết quả -

+-------------+--------------+
| FirstColumn | SecondColumn |
+-------------+--------------+
|         100 |          101 |
|         102 |          103 |
|         104 |          105 |
|         106 |          107 |
+-------------+--------------+
4 rows in set (0.00 sec)