1. 程式人生 > >[13]SQL BETWEEN 操作符

[13]SQL BETWEEN 操作符

idt over name 字母 pan where between weibo ted

[13]SQL BETWEEN 操作符

BETWEEN 操作符用於選取介於兩個值之間的數據範圍內的值。

BETWEEN 操作符選取介於兩個值之間的數據範圍內的值。這些值可以是數值、文本或者日期。

面是選自 "Websites" 表的數據:

+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/    | 1     | USA     |
| 2  | 淘寶          | https://www.taobao.com/   | 13    | CN      |
| 3  | 菜鳥教程      | http://www.runoob.com/    | 4689  | CN      |
| 4  | 微博          | http://weibo.com/         | 20    | CN      |
| 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |
| 7  | stackoverflow | http://stackoverflow.com/ |   0 | IND     |
+----+---------------+---------------------------+-------+---------+
SELECT * FROM Websites
WHERE alexa BETWEEN 1 AND 20;

技術分享

如需顯示不在上面實例範圍內的網站,請使用 NOT BETWEEN:

SELECT * FROM Websites
WHERE alexa NOT BETWEEN 1 AND 20;

技術分享

下面的 SQL 語句選取alexa介於 1 和 20 之間但 country 不為 USA 和 IND 的所有網站:

SELECT * FROM Websites
WHERE (alexa BETWEEN 1 AND 20)
AND NOT country IN (USA, IND
);

技術分享

下面的 SQL 語句選取 name 以介於 ‘A‘ 和 ‘H‘ 之間字母開始的所有網站:

SELECT * FROM Websites
WHERE name BETWEEN A AND H;

技術分享

下面的 SQL 語句選取 name 不介於 ‘A‘ 和 ‘H‘ 之間字母開始的所有網站:

SELECT * FROM Websites
WHERE name NOT BETWEEN A AND H;

技術分享

示例表

下面是 "access_log" 網站訪問記錄表的數據,其中:

  • aid:為自增 id。
  • site_id:為對應 websites表的網站 id。
  • count:訪問次數。
  • date:為訪問日期。
mysql> SELECT * FROM access_log;
+-----+---------+-------+------------+
| aid | site_id | count | date       |
+-----+---------+-------+------------+
|   1 |       1 |    45 | 2016-05-10 |
|   2 |       3 |   100 | 2016-05-13 |
|   3 |       1 |   230 | 2016-05-14 |
|   4 |       2 |    10 | 2016-05-14 |
|   5 |       5 |   205 | 2016-05-14 |
|   6 |       4 |    13 | 2016-05-15 |
|   7 |       3 |   220 | 2016-05-15 |
|   8 |       5 |   545 | 2016-05-16 |
|   9 |       3 |   201 | 2016-05-17 |
+-----+---------+-------+------------+
9 rows in set (0.00 sec)

下面的 SQL 語句選取 date 介於 ‘2016-05-10‘ 和 ‘2016-05-14‘ 之間的所有訪問記錄:

SELECT * FROM access_log
WHERE date BETWEEN 2016-05-10 AND 2016-05-14;

技術分享





[13]SQL BETWEEN 操作符