MySQL 中的 Select IN 有效嗎?


您無法執行 select IN 範圍。要獲得相同結果,請使用 BETWEEN。我們看一個示例 −

IN(start,end):指 start 和 end 之間的中間值不會顯示。對於上述邏輯,您可以使用 BETWEEN。

BETWEEN 子句是包含性的,例如,假設有 1、2、3、4、5、6 個數。如果想要包含性地顯示 2 到 6 之間的所有數,那麼使用 BETWEEN 時,也會顯示數字 2 和 6。

讓我們建立一個表 −

mysql> create table SelectInWithBetweenDemo
   -> (
   -> PortalId int
   -> );
Query OK, 0 rows affected (0.77 sec)

透過批次插入插入一些記錄。查詢如下 −

mysql> insert into SelectInWithBetweenDemo values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15);
Query OK, 15 rows affected (0.19 sec)
Records: 15 Duplicates: 0 Warnings: 0

透過 select 語句顯示所有記錄。查詢如下 −

mysql> select *from SelectInWithBetweenDemo;

以下是輸出 −

+----------+
| PortalId |
+----------+
|        1 |
|        2 |
|        3 |
|        4 |
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
|       10 |
|       11 |
|       12 |
|       13 |
|       14 |
|       15 |
+----------+
15 rows in set (0.00 sec)

現在讓我們檢查 select IN 範圍。查詢如下 −

mysql> select PortalId from SelectInWithBetweenDemo where PortalId IN(4,10);

以下是輸出 −

+----------+
| PortalId |
+----------+
|        4 |
|       10 |
+----------+
2 rows in set (0.00 sec)

觀察上面的輸出,我們僅獲得 4 和 10,而我們想要的值是 4、5、6、7、8、9、10。

現在,我們將使用 BETWEEN 子句。它將提供包含性的結果,符合我們的需要。

查詢如下 −

mysql> select PortalId from SelectInWithBetweenDemo where PortalId Between 4 and 10;

以下是輸出 −

+----------+
| PortalId |
+----------+
|        4 |
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
|       10 |
+----------+
7 rows in set (0.09 sec)

假設您需要排除性屬性,可以使用 > 和 <。查詢如下 −

mysql> select PortalId from SelectInWithBetweenDemo where PortalId > 4 and PortalId < 10;

以下是輸出 −

+----------+
| PortalId |
+----------+
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
+----------+
5 rows in set (0.00 sec)

更新於: 30-Jul-2019

5 千次瀏覽

開啟你的 職業生涯

獲得認證,完成本課程

開始學習
廣告
© . All rights reserved.