sql的嵌套查询,把一次查询的结果做为表继续进一步查询;内联视图


Mysql的嵌套表查询

  嵌套SELECT语句也叫子查询,一个 SELECT 语句的查询结果能够作为另一个语句的输入值。子查询可以:

  • 出现在Where子句中,
  • 出现在from子句中,作为一个临时表使用,
  • 出现在select list中,作为一个字段值来返回。

示例

1、出现在where子句中

  • 单行子查询 :单行子查询是指子查询的返回结果只有一行数据。当主查询语句的条件语句中引用子查询结果时可用单行比较符号(=, >, <, >=, <=, <>)来进行比较。
select ename,deptno,sal from emp where deptno=(select deptno from dept where loc='NEW YORK');
  • 多行子查询:多行子查询即是子查询的返回结果是多行数据。当主查询语句的条件语句中引用子查询结果时必须用多行比较符号(IN,ALL,ANY)来进行比较。其中,IN的含义是匹配子查询结果中的任一个值即可("IN" 操作符,能够测试某个值是否在一个列表中),ALL则必须要符合子查询的所有值才可,ANY要符合子查询结果的任何一个值即可。而且须注意ALL 和ANY 操作符不能单独使用,而只能与单行比较符(=、>、< 、>= 、<= 、<>)结合使用
select stName from Student where stId in (select distinct stId from score where teId=(select teId from teacher where teName='Rona'));
select stName from Student where stId in (select distinct stId from score where score >all (select score from score where stId=(select stId from Student where stName= 'Kaka')));
select stName from Student where stId in (select distinct stId from score where score >any(select score from score where stId=(select stId from Student where stName='Kaka')));
  • 多列子查询:当是单行多列的子查询时,主查询语句的条件语句中引用子查询结果时可用单行比较符号(=, >, <, >=, <=, <>)来进行比较;当是多行多列子查询时,主查询语句的条件语句中引用子查询结果时必须用多行比较符号(IN,ALL,ANY)来进行比较。
SELECT deptno,ename,job,sal FROM EMP WHERE (deptno,sal) IN (SELECT deptno,MAX(sal) FROM EMP GROUP BY deptno);

2、内联视图:出现在where子句中,查询结果作为子表(临时表)。示例包含联合查询、嵌套查询

select job_name1,app_name,plugin_name,plugin_version from (select job_name as job_name1, app_name as app_name,plugin_name as plugin_name,plugin_version as plugin_version from plugin_check  left join jobs  on  project_name=job_name) as suibianxie where plugin_name LIKE '%graylog-logback%' AND `plugin_version` < '1.0.27.3' ORDER BY app_name

去重复操作distinct详解

1、作用于单列自然好理解,作用于多列时,是根据多列来去重的,比如下面两列是不重复的

select distinct col1,col2,col3 from table_test
a 1 c
a 1 b

2、且distinct并非是对多列“字符串拼接”后再去重的,而是分别作用于了每一列,比如下面两列是不重复的;下面两列拼接后是相同的,但是并不会被判断会相同

select distinct col1,col2 from table_test
rain m
rai  nm

3、distinct必须放在开头

普通视图内联视图(in-line view)的关系

在select语句里的内联视图(in-line view),即SELECT * FROM (