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

MySQL lọc theo nhiều cột?

Để thực hiện lọc theo nhiều cột, hãy sử dụng mệnh đề where cùng với OR. Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(10),
   Score int
   );
Query OK, 0 rows affected (0.28 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable(Name,Score) values('John',80);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Name,Score) values('John',90);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name,Score) values('Carol',89);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Name,Score) values('John',86);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Name,Score) values('Carol',98);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name,Score) values('David',99);
Query OK, 1 row affected (0.06 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable;

Điều này sẽ tạo ra kết quả sau -

+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
| 1  | John  | 80    |
| 2  | John  | 90    |
| 3  | Carol | 89    |
| 4  | John  | 86    |
| 5  | Carol | 98    |
| 6  | David | 99    |
+----+-------+-------+
6 rows in set (0.00 sec)

Sau đây là truy vấn để thực hiện lọc theo nhiều cột -

mysql> select *from DemoTable where (Name,Score)=('John', 90) or (Name,Score)=('Carol', 98);

Điều này sẽ tạo ra kết quả sau -

+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
| 2  | John  | 90    |
| 5  | Carol | 98    |
+----+-------+-------+
2 rows in set (0.00 sec)