介紹如何在 MySQL/MariaDB 資料庫中使用 BETWEEN
設定區間篩選條件。
為了示範 BETWEEN
使用方式,我們先建立測試用的 products
資料表:
-- 建立 products 資料表 CREATE TABLE products ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), price INT UNSIGNED, last_update DATE, PRIMARY KEY (id) );
插入一些測試用的資料:
-- 新增資料 INSERT INTO products (name, price, last_update) VALUES ("A031", 320, "2015-10-14"), ("C001", 420, "2013-03-08"), ("B021", 280, "2013-12-02"), ("Y158", 690, "2015-11-21"), ("A202", 195, "2019-02-23"), ("D022", 540, "2017-03-19");
顯示測試用的資料:
-- 顯示所有資料 SELECT * FROM products;
+----+------+-------+-------------+ | id | name | price | last_update | +----+------+-------+-------------+ | 1 | A031 | 320 | 2015-10-14 | | 2 | C001 | 420 | 2013-03-08 | | 3 | B021 | 280 | 2013-12-02 | | 4 | Y158 | 690 | 2015-11-21 | | 5 | A202 | 195 | 2019-02-23 | | 6 | D022 | 540 | 2017-03-19 | +----+------+-------+-------------+
BETWEEN
區間條件BETWEEN
可設定一個區間,用來篩選連續性的資料類型,例如篩選 price
介於 200
至 400
之間的資料:
-- 篩選 price 介於 200 至 400 之間的資料 SELECT * FROM products WHERE price BETWEEN 200 AND 400;
+----+------+-------+-------------+ | id | name | price | last_update | +----+------+-------+-------------+ | 1 | A031 | 320 | 2015-10-14 | | 3 | B021 | 280 | 2013-12-02 | +----+------+-------+-------------+
上面這個 BETWEEN
的條件也可以寫成這樣,效果相同:
-- 篩選 price 介於 200 至 400 之間的資料 SELECT * FROM products WHERE price >= 200 AND price <= 400;
加上 NOT
就可以篩選 price
不介於 200
至 400
之間的資料:
-- 篩選 price 不介於 200 至 400 之間的資料 SELECT * FROM products WHERE price NOT BETWEEN 200 AND 400;
+----+------+-------+-------------+ | id | name | price | last_update | +----+------+-------+-------------+ | 2 | C001 | 420 | 2013-03-08 | | 4 | Y158 | 690 | 2015-11-21 | | 5 | A202 | 195 | 2019-02-23 | | 6 | D022 | 540 | 2017-03-19 | +----+------+-------+-------------+
除了數值之外,BETWEEN
亦可用於日期或時間的篩選,例如篩選 last_update
介於 2015-01-01
至 2017-06-01
之間的資料:
-- 篩選 last_update 介於 2015-01-01 至 2017-06-01 之間的資料 SELECT * FROM products WHERE last_update BETWEEN "2015-01-01" AND "2017-06-01";
+----+------+-------+-------------+ | id | name | price | last_update | +----+------+-------+-------------+ | 1 | A031 | 320 | 2015-10-14 | | 4 | Y158 | 690 | 2015-11-21 | | 6 | D022 | 540 | 2017-03-19 | +----+------+-------+-------------+