介紹如何在 MySQL/MariaDB 資料庫中使用 DELETE
指令刪除指定的資料。
為了示範 DELETE
指令的使用方式,我們先建立測試用的 products
資料表:
-- 建立 products 資料表 CREATE TABLE products ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), price INT UNSIGNED, inventory INT UNSIGNED, last_update DATE, PRIMARY KEY (id) );
再插入一些測試用的資料:
-- 新增資料 INSERT INTO products (name, price, inventory, last_update) VALUES ("A031", 320, 9, "2015-10-14"), ("C001", 420, 0, "2013-03-08"), ("B021", 280, 3, "2013-12-02"), ("Y158", 690, 4, "2015-11-21"), ("A202", 195, 1, "2019-02-23"), ("D022", 540, 5, "2017-03-19");
顯示測試用的資料:
-- 顯示所有資料 SELECT * FROM products;
+----+------+-------+-----------+-------------+ | id | name | price | inventory | last_update | +----+------+-------+-----------+-------------+ | 1 | A031 | 320 | 9 | 2015-10-14 | | 2 | C001 | 420 | 0 | 2013-03-08 | | 3 | B021 | 280 | 3 | 2013-12-02 | | 4 | Y158 | 690 | 4 | 2015-11-21 | | 5 | A202 | 195 | 1 | 2019-02-23 | | 6 | D022 | 540 | 5 | 2017-03-19 | +----+------+-------+-----------+-------------+
DELETE
刪除資料DELETE
可以用來刪除資料表中指定的資料,例如刪除 id
為 5
的那一筆資料:
-- 刪除 id 為 5 的資料 DELETE FROM products WHERE id = 5;
接著查看刪除後的結果:
-- 顯示所有資料 SELECT * FROM products;
+----+------+-------+-----------+-------------+ | id | name | price | inventory | last_update | +----+------+-------+-----------+-------------+ | 1 | A031 | 320 | 9 | 2015-10-14 | | 2 | C001 | 420 | 0 | 2013-03-08 | | 3 | B021 | 280 | 3 | 2013-12-02 | | 4 | Y158 | 690 | 4 | 2015-11-21 | | 6 | D022 | 540 | 5 | 2017-03-19 | +----+------+-------+-----------+-------------+
若要一次刪除多筆資料,可以使用 IN
清單條件指定多個 id
:
-- 刪除 id 為 1, 4 的資料 DELETE FROM products WHERE id IN (1, 4); -- 顯示所有資料 SELECT * FROM products;
+----+------+-------+-----------+-------------+ | id | name | price | inventory | last_update | +----+------+-------+-----------+-------------+ | 2 | C001 | 420 | 0 | 2013-03-08 | | 3 | B021 | 280 | 3 | 2013-12-02 | | 6 | D022 | 540 | 5 | 2017-03-19 | +----+------+-------+-----------+-------------+
若要刪除指定時間區間內的資料,則可使用 BETWEEN
區間條件:
-- 刪除 last_update 介於 2013-01-01 與 2013-12-31 的資料 DELETE FROM products WHERE last_update BETWEEN "2013-01-01" AND "2013-12-31"; -- 顯示所有資料 SELECT * FROM products;
+----+------+-------+-----------+-------------+ | id | name | price | inventory | last_update | +----+------+-------+-----------+-------------+ | 6 | D022 | 540 | 5 | 2017-03-19 | +----+------+-------+-----------+-------------+
若不加任何的資料篩選條件,DELETE
就會將整張資料表內所有的資料都刪除:
-- 清空 products 資料表 DELETE FROM products;