在 MySQL 中的多个列中搜索行匹配项


为此,使用 UNION。我们首先创建一个表 −

mysql> create table DemoTable645 (Id int,FirstName varchar(100));
Query OK, 0 rows affected (0.67 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable645 values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable645 values(101,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable645 values(101,'Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable645 values(102,'Carol');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable645 values(100,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable645 values(100,'Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable645 values(101,'Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable645 values(101,'John');
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable645;

这将产生以下输出 −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  100 | Chris     |
|  101 | Robert    |
|  101 | Bob       |
|  102 | Carol     |
|  100 | John      |
|  100 | Robert    |
|  101 | Mike      |
|  101 | John      |
+------+-----------+
8 rows in set (0.00 sec)

以下是搜索多个列的查询 −

mysql> select Id AS Records from DemoTable645 where Id LIKE '%100%'
   union
   select FirstName from DemoTable645 where FirstName LIKE '%John%'
   order by 1 LIMIT 3;

这将产生以下输出 −

+---------+
| Records |
+---------+
| 100     |
| John    |
+---------+
2 rows in set (0.00 sec)

更新日期:2019 年 8 月 23 日

379 次浏览

开启您的 职业生涯

完成课程,获得认证

开始
广告