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

Truy vấn MySQL để trả về nhiều bản ghi hàng với toán tử AND &OR

Đầ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(40),
   StudentMathMarks int,
   StudentMySQLMarks int,
   status ENUM('ACTIVE','INACTIVE')
);
Query OK, 0 rows affected (0.47 sec)

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

mysql> insert into DemoTable(StudentName,StudentMathMarks,StudentMySQLMarks,status) values('Chris',45,67,'active');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentName,StudentMathMarks,StudentMySQLMarks,status) values('Bob',89,78,'inactive');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentName,StudentMathMarks,StudentMySQLMarks,status) values('David',56,68,'active');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName,StudentMathMarks,StudentMySQLMarks,status) values('Robert',68,75,'active');
Query OK, 1 row affected (0.18 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 -

+-----------+-------------+------------------+-------------------+----------+
| StudentId | StudentName | StudentMathMarks | StudentMySQLMarks | status   |
+-----------+-------------+------------------+-------------------+----------+
|         1 | Chris       |               45 |                67 | ACTIVE   |
|         2 | Bob         |               89 |                78 | INACTIVE |
|         3 | David       |               56 |                68 | ACTIVE   |
|         4 | Robert      |               68 |                75 | ACTIVE   |
+-----------+-------------+------------------+-------------------+----------+
4 rows in set (0.00 sec)

Sau đây là truy vấn để trả về nhiều bản ghi hàng với toán tử AND &OR -

mysql> select *from DemoTable
   where status='active'
and (StudentMathMarks=68 or StudentMySQLMarks=67);

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

+-----------+-------------+------------------+-------------------+--------+
| StudentId | StudentName | StudentMathMarks | StudentMySQLMarks | status |
+-----------+-------------+------------------+-------------------+--------+
|         1 | Chris       |               45 |                67 | ACTIVE |
|         4 | Robert      |               68 |                75 | ACTIVE |
+-----------+-------------+------------------+-------------------+--------+
2 rows in set (0.00 sec)