在where子句的帮助下实现这一目标。
语法如下
SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName WHERE ( SELECT COUNT(*) FROM yourTableName )=2;
为了理解这个概念,让我们创建一个表。创建表的查询如下
mysql> create table CountWithSubqueryDemo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > EmployeeName varchar(20) - > );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into CountWithSubqueryDemo(EmployeeName) values('John'); mysql> insert into CountWithSubqueryDemo(EmployeeName) values(NULL); mysql> insert into CountWithSubqueryDemo(EmployeeName) values('Carol'); mysql> insert into CountWithSubqueryDemo(EmployeeName) values(''); mysql> insert into CountWithSubqueryDemo(EmployeeName) values('Bob'); mysql> insert into CountWithSubqueryDemo(EmployeeName) values(NULL); mysql> insert into CountWithSubqueryDemo(EmployeeName) values('Sam'); mysql> insert into CountWithSubqueryDemo(EmployeeName) values('Mike'); mysql> insert into CountWithSubqueryDemo(EmployeeName) values('James');
使用select语句显示表中的所有记录。
查询如下
mysql> select *from CountWithSubqueryDemo;
以下是输出
+----+--------------+ | Id | EmployeeName | +----+--------------+ | 1 | John | | 2 | NULL | | 3 | Carol | | 4 | | | 5 | Bob | | 6 | NULL | | 7 | Sam | | 8 | Mike | | 9 | James | +----+--------------+ 9 rows in set (0.19 sec)
以下是如何在where子句中使用实际行数
mysql> select Id,EmployeeName from CountWithSubqueryDemo - > where - > ( - > select count(*) from CountWithSubqueryDemo - > )=2; Empty set (0.03 sec)
在上面的查询中,我们得到空集,因为如果表只有两个记录,它将返回行。因此,让我们从表中删除所有记录,并在表中插入2条记录。
查询如下
mysql> truncate table CountWithSubqueryDemo;
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into CountWithSubqueryDemo(EmployeeName) values('James'); mysql> insert into CountWithSubqueryDemo(EmployeeName) values(NULL);
使用select语句显示表中的所有记录。
查询如下
mysql> select *from CountWithSubqueryDemo;
以下是输出
+----+--------------+ | Id | EmployeeName | +----+--------------+ | 1 | James | | 2 | NULL | +----+--------------+ 2 rows in set (0.00 sec)
现在,以下是where子句中的行计数查询
mysql> select Id,EmployeeName from CountWithSubqueryDemo - > where - > ( - > select count(*) from CountWithSubqueryDemo - > )=2;
以下是输出
+----+--------------+ | Id | EmployeeName | +----+--------------+ | 1 | James | | 2 | NULL | +----+--------------+ 2 rows in set (0.00 sec)