Select 0: 

写法1:

select * from tab a where exists (select 0 from tab b where a.id = b.id)

写法2:

select * from tab a where exists (select * from tab b where a.id = b.id)

select 0在这里没有意义 这样写可以提高查询速度 因为不用在展现真实数据,与上边效果一样 上边的效率更高。

当我们只关心数据表有多少记录行而不需要知道具体的字段值时,类似“select 1 from tblName”是一个很不错的SQL语句写法,它通常用于子查询。这样可以减少系统开销,提高运行效率,因为这样子写的SQL语句,数据库引擎就不会去检索数据表里一条条具体的记录和每条记录里一个个具体的字段值并将它们放到内存里,而是根据查询到有多少行存在就输出多少个“1”,每个“1”代表有1行记录,同时选用数字1还因为它所占用的内存空间最小,当然用数字0的效果也一样。在不需要知道具体的记录值是什么的情况下这种写法无疑更加可取。
下面举例示范这种写法的常见用法:

常规写法:

select class, count (*)  as  pax  from  students group  by  class;

更优写法:

select  class, count  (1)  as  pax  from  students group  by  class;

2)列出每个班最年轻的学生资料

常规写法:

select  a.*  from  students a  where  not  exists( select  b.sid  from  students b  where  b.sid=a.sid and b.date_birth>a.date_birth);

更优写法:

select a.*  from  students a  where  not  exists ( select  1  from  students b  where  b.sid=a.sid and b.date_birth > a.date_birth);

总结:

select 1 from table; 与 select anycol (目的表集合中的任意一行)from table; 与 select * from table 从作用上来说是没有差别的,都是查看是否有记录,一般是作条件查询用的。

select 1 from 中的1是一常量(可以为任意数值), 查到的所有行的值都是它,但从效率上来说,1 > anycol >*,因为不用查字典表。
 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐