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

Làm thế nào để làm việc với nhiều điều kiện AND trong MySQL?

Để làm việc với nhiều điều kiện AND trong MySQL, sau đây là cú pháp -

select *from yourTableName where yourColumnName1=yourValue1 and yourColumnName2=yourValue2 and yourColumnName3=yourValue3;

Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20),
   StudentAge int,
   StudentCountryName varchar(40)
   );
Query OK, 0 rows affected (0.59 sec)

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

mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('John',23,'US');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('Carol',21,'UK');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('John',21,'US');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('John',21,'AUS');
Query OK, 1 row affected (0.14 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;

Đầu ra

+-----------+-------------+------------+--------------------+
| StudentId | StudentName | StudentAge | StudentCountryName |
+-----------+-------------+------------+--------------------+
| 1         | John        | 23         | US                 |
| 2         | Carol       | 21         | UK                 |
| 3         | John        | 21         | US                 |
| 4         | John        | 21         | AUS                |
+-----------+-------------+------------+--------------------+
4 rows in set (0.00 sec)

Sau đây là truy vấn cho nhiều điều kiện AND trong MySQL -

mysql> select *from DemoTable where StudentName="John" and StudentAge=21 and StudentCountryName="AUS";

Đầu ra

+-----------+-------------+------------+--------------------+
| StudentId | StudentName | StudentAge | StudentCountryName |
+-----------+-------------+------------+--------------------+
| 4         | John        | 21         | AUS                |
+-----------+-------------+------------+--------------------+
1 row in set (0.00 sec)