如何正确将子查询括在MySQL中?

您需要在圆括号中关闭子查询。语法如下-

select if((select count(*) from yourTableName ),'Yes','No') as anyAliasName;

为了理解上述语法,让我们创建一个表。创建表的查询如下-

mysql> create table SelectIfDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(10)
   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into SelectIfDemo(Name) values('John');
mysql> insert into SelectIfDemo(Name) values('Carol');
mysql> insert into SelectIfDemo(Name) values('Larry');
mysql> insert into SelectIfDemo(Name) values('Bob');
mysql> insert into SelectIfDemo(Name) values('Sam');

现在,您可以使用select语句显示表中的所有记录。查询如下-

mysql> select *from SelectIfDemo;

以下是输出-

+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Carol |
|  3 | Larry |
|  4 | Bob   |
|  5 | Sam   |
+----+-------+
5 rows in set (0.00 sec)

这是在括号内使用子查询的正确方法。查询如下-

mysql> select if((select count(*) from SelectIfDemo),'Yes','No') as Result;

以下是输出-

+--------+
| Result |
+--------+
| Yes    |
+--------+
1 row in set (0.00 sec)