当我们只关心数据表有多少记录行而不需要知道具体的字段值时,类似“select 1 from tblName”是一个很不错的SQL语句写法,它通常用于子查询。这样可以减少系统开销,提高运行效率,因为这样子写的SQL语句,数据库引擎就不会去检索数据表里一条条具体的记录和每条记录里一个个具体的字段值并将它们放到内存里,而是根据查询到有多少行存在就输出多少个“1”,每个“1”代表有1行记录,同时选用数字1还因为它所占用的内存空间最小,当然用数字0的效果也一样。在不需要知道具体的记录值是什么的情况下这种写法无疑更加可取。
下面举例示范这种写法的常见用法:
1)列出每个班的学生人数
常规写法
1
2
|
select
class,
count
(*)
as
pax
from
students
group
by
class;
|
更优写法
1
2
|
select
class,
count
(1)
as
pax
from
students
group
by
class;
|
2)列出每个班最年轻的学生资料
常规写法
1
2
3
|
select
a.*
from
students a
where
not
exists(
select
from
students b
where
=
and
b.date_birth>a.date_birth);
|
更优写法
1
2
3
|
select
a.*
from
students a
where
not
exists(
select
1
from
students b
where
=
and
b.date_birth>a.date_birth);
|