在 MySQL 中的 SELECT 語句中追加萬用字元嗎?


對於追加,使用 concat() 的概念。語法如下 −

select *from yourTableName where yourColumnName like concat('%',yourValue,'%');

讓我們建立一個表 −

mysql> create table demo48
-> (
−> id int not null auto_increment primary key,
−> name varchar(20)
−> );
Query OK, 0 rows affected (0.70 sec)

使用 insert 命令將一些記錄插入到表中 −

mysql> insert into demo48(name) values('John Smith');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo48(name) values('John Doe');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo48(name) values('Adam Smith');
Query OK, 1 row affected (0.23 sec)

mysql> insert into demo48(name) values('David Miller');
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo48(name) values('Chris Brown');
Query OK, 1 row affected (0.11 sec)

使用 select 語句從表中顯示記錄 −

mysql> select *from demo48;

這將生成以下輸出 −

+----+--------------+
| id | name         |
+----+--------------+
|  1 | John Smith   |
|  2 | John Doe     |
|  3 | Adam Smith   |
|  4 | David Miller |
|  5 | Chris Brown  |
+----+--------------+
5 rows in set (0.00 sec)

以下是在 select 語句中追加萬用字元的查詢 −

mysql> select *from demo48 where name like concat('%','Smith','%');

這將生成以下輸出 −

+----+------------+
| id | name       |
+----+------------+
|  1 | John Smith |
|  3 | Adam Smith |
+----+------------+
2 rows in set (0.00 sec)

更新時間: 2020-11-19

99 人次瀏覽

開始你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.