如何在 MySQL 中检查多个列中的单个值?
mysqlmysqli database
您可以借助 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)
使用 insert 语句在表中插入一些记录。查询如下 −
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)
以下是检查多列中单个值的查询。我们在多列中检查值"Taylor",即 StudentId、StudentFirstname、StudentLastname 和 StudentAge。
查询如下 −
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)