如何在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 −> );
借助select语句在表中插入一些记录。查询如下-
mysql> insert into OneValueFromAllColumns values(1,'John','Smith',23); mysql> insert into OneValueFromAllColumns values(2,'Carol','Taylor',22); mysql> insert into OneValueFromAllColumns values(3,'Maria','Garcia',19); mysql> insert into OneValueFromAllColumns values(4,'Bob','Wilson',21);
显示我们在上方插入的所有记录。显示表中所有记录的查询如下-
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)