如何在 MySQL 中为单个值检查多列?
使用 IN 运算符,可以为一个值检查多列。语法如下 −
select *from yourTableName where value IN(yourColumnName1, yourColumnName2,......N);
为了理解上述概念,我们创建一张包含一些列的表。创建表的查询如下 −
mysql> create table OneValueFromAllColumns −> ( −> StudentId int, −> StudentFirstname varchar(200), −> StudentLastname varchar(200), −> StudentAge int −> ); Query OK, 0 rows affected (1.41 sec)
使用 select 语句在表中插入一些记录。查询如下 −
mysql> insert into OneValueFromAllColumns values(1,'John','Smith',23); Query OK, 1 row affected (0.14 sec) mysql> insert into OneValueFromAllColumns values(2,'Carol','Taylor',22); Query OK, 1 row affected (0.18 sec) mysql> insert into OneValueFromAllColumns values(3,'Maria','Garcia',19); Query OK, 1 row affected (0.16 sec) mysql> insert into OneValueFromAllColumns values(4,'Bob','Wilson',21); Query OK, 1 row affected (0.22 sec)
显示我们上面插入的所有记录。从表中显示所有记录的查询如下 −
mysql> select *from OneValueFromAllColumns;
以下是输出 −
+-----------+------------------+-----------------+------------+ | StudentId | StudentFirstname | StudentLastname | StudentAge | +-----------+------------------+-----------------+------------+ | 1 | John | Smith | 23 | | 2 | Carol | Taylor | 22 | | 3 | Maria | Garcia | 19 | | 4 | Bob | Wilson | 21 | +-----------+------------------+-----------------+------------+ 4 rows in set (0.00 sec)
以下是为单个值检查多列的查询。我们正在检查多列(即 StudentId、StudentFirstname、StudentLastname 和 StudentAge)中的值“Taylor”。
查询如下 −
mysql> select *from OneValueFromAllColumns where 'Taylor' IN(StudentId,StudentFirstname,StudentLastname,StudentAge);
以下是显示值“Taylor”的记录的输出 −
+-----------+------------------+-----------------+------------+ | StudentId | StudentFirstname | StudentLastname | StudentAge | +-----------+------------------+-----------------+------------+ | 2 | Carol | Taylor | 22 | +-----------+------------------+-----------------+------------+ 1 row in set, 4 warnings (0.03 sec)
广告