我們在 MySql 中可以同時使用 LIKE 和 OR 嗎?


可以使用 LIKE 運算子,其作用與 IN 運算子相同。

讓我們看看這兩種情況的語法:

用例 1 - 使用 LIKE 和 OR 運算子。

select *from yourTableName where yourColumnName Like ‘Value1’
or yourColumnName Like ‘Value2’
or yourColumnName Like ‘Value3’
.
.
.
N

用例 2 - 使用 IN 運算子。

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

為了理解這兩個語法,我們建立一個表。建立表的查詢如下:

mysql> create table LikeDemo
−> (
−> Id varchar(20)
−> );
Query OK, 0 rows affected (0.58 sec)

現在你可以使用插入語句將記錄插入到表中。查詢如下:

mysql> insert into LikeDemo values('John123');
Query OK, 1 row affected (0.22 sec)

mysql> insert into LikeDemo values('Smith205');
Query OK, 1 row affected (0.18 sec)

mysql> insert into LikeDemo values('Bob999');
Query OK, 1 row affected (0.18 sec)

mysql> insert into LikeDemo values('Carol9091');
Query OK, 1 row affected (0.17 sec)

mysql> insert into LikeDemo values('Johnson2222');
Query OK, 1 row affected (0.15 sec)

mysql> insert into LikeDemo values('David2345');
Query OK, 1 row affected (0.21 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下:

mysql> select *from LikeDemo;

以下是輸出:

+-------------+
| Id          |
+-------------+
| John123     |
| Smith205    |
| Bob999      |
| Carol9091   |
| Johnson2222 |
| David2345   |
+-------------+
6 rows in set (0.00 sec)

以下查詢使用 LIKE 和 OR 運算子:

用例 1 - 使用 LIKE 和 OR 運算子

mysql> select *from LikeDemo where Id Like 'John123%' or Id Like 'Carol9091%' or Id Like 'David2345%';

以下是輸出:

+-----------+
| Id        |
+-----------+
| John123   |
| Carol9091 |
| David2345 |
+-----------+
3 rows in set (0.00 sec)

用例 2 - 使用 IN 運算子

查詢如下:

mysql> select *from LikeDemo where Id in('John123','Carol9091', 'David2345');

以下是輸出:

+-----------+
| Id        |
+-----------+
| John123   |
| Carol9091 |
| David2345 |
+-----------+
3 rows in set (0.04 sec)

更新於:2020 年 6 月 29 日

17K+ 訪問量

啟動你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.