使用 LIKE 運算子查詢多個欄位上具有相同值的 MySQL 查詢?


我們首先建立一個表 -

mysql> create table DemoTable
   ->
   -> (
   -> StudentName varchar(20),
   -> StudentSubject varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values('John','MySQL');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Adam','MySQL');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('John','Java');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values('Carol','Java');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('John','MongoDB');
Query OK, 1 row affected (0.12 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

這將生成以下輸出 -

+-------------+----------------+
| StudentName | StudentSubject |
+-------------+----------------+
| John        | MySQL          |
| Adam        | MySQL          |
| John        | Java           |
| Carol       | Java           |
| John        | MongoDB        |
+-------------+----------------+
5 rows in set (0.00 sec)

以下是使用 like 運算子查詢多個欄位上具有相同值的查詢 -

mysql> select *from DemoTable
   -> where concat(StudentName,' ',StudentSubject)
   -> like '%John MySQL%';

這將生成以下輸出 -

+-------------+----------------+
| StudentName | StudentSubject |
+-------------+----------------+
| John        | MySQL          |
+-------------+----------------+
1 row in set (0.00 sec)

更新於: 12-Dec-2019

486 瀏覽量

開啟你的 職業生涯

完成課程認證

立即開始
廣告