select 1 from ... sql语句中的1代表什么意思?

原文链接 :https://blog.csdn.net/bibibrave/article/details/82961201

我们都知道,用exists代替in可以提高sql语句的执行效率,例如如下两个例子:
检索部门所在地为 NEW YORK’的员工信息。

使用IN

select * from scott.emp
 where deptno in (
  select deptno from scott.dept where loc='NEW YORK');

  使用 exists

select * from scott.emp
 where  exists (
  select 1 from scott.dept where scott.dept.deptno=scott.emp.deptno and  loc='NEW YORK');

注意,这里出现了一个特殊用法select 1 ?
比如说,使用select 1 from table的结果是临时得到1列(列的值为1),其行数为表的记录数(行数),如果配合exists 语句则可以快速查询结果是否存在,而结果的具体数据不涉及到。
就像我上述提供的例子,它只查询验证dept表的字段deptno和emp的字段deptno是否有相等的情况,并且loc=‘NEW YORK’,而不需要知道dept表和emp表哪些记录存在那样的情况,也不需要知道相等情况下其他字段的值。在应用中,效率比select * 快。
扩展: select 1 from table;与select anycol(目的表集合中的任意一行) from table;与select * from table 从作用上来说是没有差别的,都是查看是否有记录,一般是作条件查询用的。select 1 from 中的1是一常量(可以为任意数值),查到的所有行的值都是它,但从效率上来说,1>anycol>*,因为不用查字典表。

 

上一篇:《UNIX环境高级编程》笔记——1.UNIX基础知识


下一篇:hive-DML-查询-join语句