使用 MySQL 根據第一個字元過濾列值


你可以使用 MySQL 中的 LEFT() 函式。我們首先建立一個 −

mysql> create table DemoTable1428
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20)
   -> );
Query OK, 0 rows affected (1.05 sec)

使用 insert 在表中插入一些記錄 −

mysql> insert into DemoTable1428(EmployeeName) values('Chris Brown');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1428(EmployeeName) values('Bob Brown');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1428(EmployeeName) values('John Smith');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1428(EmployeeName) values('David Miller');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1428(EmployeeName) values('John Doe');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1428(EmployeeName) values('Carol Johnson');
Query OK, 1 row affected (0.16 sec)

使用 select 顯示錶中的所有記錄 −

mysql> select * from DemoTable1428;

這將生成以下輸出 −

+------------+---------------+
| EmployeeId | EmployeeName  |
+------------+---------------+
|          1 | Chris Brown   |
|          2 | Bob Brown     |
|          3 | John Smith    |
|          4 | David Miller  |
|          5 | John Doe      |
|          6 | Carol Johnson |
+------------+---------------+
6 rows in set (0.00 sec)

以下是透過第一個字元來過濾列值的查詢 −

mysql> select * from DemoTable1428 where left(EmployeeName,1)='J';

這將生成以下輸出 −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|          3 | John Smith   |
|          5 | John Doe     |
+------------+--------------+
2 rows in set (0.00 sec)

更新於: 12-11-2019

1K+ 次瀏覽

開啟你的 職業生涯

完成本課程即可獲得證書

開始
廣告