MySQL SQL中select 1的作用【转】

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

下面举例示范这种写法的常见用法:

1)列出每个班的学生人数

常规写法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 中的1是一常量(可以为任意数值),查到的所有行的值都是它,但从效率上来说,1>anycol>*,因为不用查字典表。 

转自

(3条消息) mysql中1代表什么_select 1 from sql语句中的1代表什么意思_令狐星尘的博客-CSDN博客
https://blog.csdn.net/weixin_36153937/article/details/113980473?utm_term=1%E7%9A%84%E4%BD%9C%E7%94%A8mysqlselect&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-1-113980473&spm=3001.4430

mysql – 在查询“SELECT 1 …”中使用“LIMIT 1”是否有意义? - 程序园
http://www.voidcn.com/article/p-gqyjwray-bup.html

(3条消息) select 1 from dual 中的1表示的含义_pear86743的专栏-CSDN博客
https://blog.csdn.net/pear86743/article/details/78204180

(3条消息) select 1 from ... sql语句中的1代表什么意思?_wolovedaima123的博客-CSDN博客
https://blog.csdn.net/wolovedaima123/article/details/81070484

原文地址:https://www.cnblogs.com/paul8339/p/14684400.html