MariaDB刪除資料


MariaDB DELETE語句用於從MariaDB資料庫的表中刪除一個或多個記錄。

語法:

DELETE FROM table  
[WHERE conditions]  
[ORDER BY expression [ ASC | DESC ]]  
[LIMIT number_rows];

1. 使用條件刪除資料

下面演示如何使用指定的一個條件來刪除資料。

範例:

DELETE FROM Students  
WHERE student_name = 'Blaba';

在執行上面刪除語句後,現在查詢表中的資料 -

2. 使用多個條件刪除資料

假設資料庫表students中的student_name有兩個Maxsu值,現在想刪除student_id不是1的所有Maxsu值,參考以下語句 -

首先插入兩條件記錄 -

INSERT INTO Students  
(student_name, student_address, admission_date) 
VALUES('Maxsu','Sanya','2016-03-09 00:00:00');
-- 再插入另一條記錄
INSERT INTO Students  
(student_name, student_address, admission_date) 
VALUES('Ajeet','Sanya','2015-12-07 00:00:00');

查詢當資料庫中的記錄 -

MariaDB [testdb]> select * from students;
+------------+--------------+-----------------+----------------+
| student_id | student_name | student_address | admission_date |
+------------+--------------+-----------------+----------------+
|          1 | Maxsu        | Haikou          | 2017-01-07     |
|          3 | JMaster      | Beijing         | 2016-05-07     |
|          4 | Mahesh       | Guangzhou       | 2016-06-07     |
|          5 | 科比         | Haikou          | 2016-02-07     |
|          7 | Maxsu        | Sanya           | 2016-03-09     |
|          8 | Ajeet        | Sanya           | 2015-12-07     |
+------------+--------------+-----------------+----------------+
6 rows in set (0.00 sec)

刪除那些student_id大於1,並且student_nameMaxsu的記錄 -

DELETE FROM Students
WHERE student_name = 'Maxsu'
AND student_id > 1;

執行上面刪除語句以後,現在查詢表中的記錄 -

MariaDB [testdb]> select * from students;
+------------+--------------+-----------------+----------------+
| student_id | student_name | student_address | admission_date |
+------------+--------------+-----------------+----------------+
|          1 | Maxsu        | Haikou          | 2017-01-07     |
|          3 | JMaster      | Beijing         | 2016-05-07     |
|          4 | Mahesh       | Guangzhou       | 2016-06-07     |
|          5 | 科比         | Haikou          | 2016-02-07     |
|          8 | Ajeet        | Sanya           | 2015-12-07     |
+------------+--------------+-----------------+----------------+
5 rows in set (0.00 sec)

可以看到,student_id7,並且student_name值為Maxsu的記錄被刪除了。