MySQL選擇多個值?


要選擇多個值,可以使用 WHERE 子句以及 OR 和 IN 運算子。

語法如下 −

情況 1 − 使用 OR

select *from yourTablename where yourColumnName = value1 or yourColumnName = value2 or yourColumnName = value3,.........N;

情況 2 − 使用 IN

select *from yourTableName where yourColumnName IN(value1,value2,....N);

為理解以上語法,我們建立一個表。以下查詢用於建立表 −

mysql> create table selectMultipleValues
−> (
−> BookId int,
−> BookName varchar(200)
−> );
Query OK, 0 rows affected (1.68 sec)

現在,你可以藉助 insert 命令向表中插入一些記錄。插入記錄的查詢如下 −

mysql> insert into selectMultipleValues values(100,'Introduction to C');
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectMultipleValues values(101,'Introduction to C++');
Query OK, 1 row affected (0.19 sec)

mysql> insert into selectMultipleValues values(103,'Introduction to java');
Query OK, 1 row affected (0.14 sec)

mysql> insert into selectMultipleValues values(104,'Introduction to Python');
Query OK, 1 row affected (0.14 sec)

mysql> insert into selectMultipleValues values(105,'Introduction to C#');
Query OK, 1 row affected (0.13 sec)

mysql> insert into selectMultipleValues values(106,'C in Depth');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from selectMultipleValues;

輸出如下 −

+--------+------------------------+
| BookId | BookName               |
+--------+------------------------+
| 100    | Introduction to C      |
| 101    | Introduction to C++    |
| 103    | Introduction to java   |
| 104    | Introduction to Python |
| 105    | Introduction to C#     |  
| 106    | C in Depth             |
+--------+------------------------+
6 rows in set (0.00 sec)

以下查詢使用 OR 運算子選擇多個值。

情況 1 − 使用 OR 運算子。

mysql> select *from selectMultipleValues where BookId = 104 or BookId = 106;

輸出如下 −

+--------+------------------------+
| BookId | BookName |
+--------+------------------------+
| 104 | Introduction to Python |
| 106 | C in Depth |
+--------+------------------------+
2 rows in set (0.00 sec)

情況 2 − 使用 IN 運算子。

以下查詢使用 IN 運算子選擇多個值。

mysql> select *from selectMultipleValues where BookId in(104,106);

輸出如下 −

+--------+------------------------+
| BookId | BookName               |
+--------+------------------------+
| 104    | Introduction to Python |
| 106    | C in Depth             |  
+--------+------------------------+
2 rows in set (0.00 sec)

更新於: 2020 年 6 月 29 日

20,000+ 次瀏覽

啟動你的 職業

完成課程後獲得認證

開始
廣告