码迷,mamicode.com
首页 > 其他好文 > 详细

嵌套查询及其作用域:

时间:2018-08-16 00:55:04      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:垂直   过滤   .com   聚合函数   order by   来源   from   role   nio   

近日整理数据库中的点单规则数据时,在写SQL语句时遇到了一个bug,解决办法以及原因整理出来。

事例SQL,

(select city.cityName as ‘城市‘,cdr.role as ‘角色‘,cdr.buildType as ‘规则‘,city.companyName as ‘规则code‘,cdr.filter as ‘区域‘
from config_diandan_rule cdr ,(select cityCode,cityName,companyCode,companyName from gte_app_config) as city
where city.cityCode = cdr.appId and city.companyCode = cdr.value and status = 1 and type = 1 and cdr.buildType like ‘ALL‘
order by cityName)
union
(select city.cityName as ‘城市‘,cdr.role as ‘角色‘,cdr.buildType as ‘规则‘,cdr.value as ‘规则code‘,dictDict.dict_name as ‘区域‘
from config_diandan_rule cdr,
(select gac.cityCode,gac.cityName from gte_app_config gac) as city,
(select tdd.dict_name from t_dictionary_dict tdd,config_diandan_rule cdr,
(select tdt.data_key from t_dictionary_type tdt ,config_diandan_rule cdr where tdt.app_id = cdr.appId and tdt.data_key_name like ‘XING_ZHENG_QU_YU‘) as dictType
where tdd.dict_type = dictType.data_key and tdd.dict_code = cdr.filter) as dictDict
where city.cityCode = cdr.appId and status = 1 and type = 1 and cdr.buildType like ‘QUYU_PERSON‘
order by city.cityName);

 

嵌套查询具有垂直上下之关系,没有水平扩展之联系。

 

相关知识点延伸:

 

SQL语句执行时的顺序:

在SQL中,经常用到的关键字有select,from,where,group by,order by,having。其中select,from是必须有的,其他是可选的。它们执行的顺序为from--where--group by--having--select--order by。

from:表示数据来源,从哪些表中获取数据;

where:表示获取满足条件的数据,满足条件的数据获取到内存中;

group by:对从where过滤出的数据进行分组

having:对分组后的数据进行过滤,此时过滤的条件不同于where,having是以分组后的结果作为条件(选出相应的分组),且having只能用于聚合函数

select:返回相应的数据

order by:以什么样的数据来查看返回的数据,对返回的数据进行排序

 

from后的表相关联,是从右往左进行解析的;

where:where条件的解析是自下向上的。

了解这些规则,我们进而写出高效的sql语句,比如把大表放在from子句的右边,将过滤最多的条件放在where子句的下边,这一点感觉影响不大,不如建合适的索引。

同时,知道了这些规则,我们就会明白上述sql是否正确,在嵌套查询中相关表的作用域,是否有必要再次关联。

 

嵌套查询及其作用域:

标签:垂直   过滤   .com   聚合函数   order by   来源   from   role   nio   

原文地址:https://www.cnblogs.com/gulingjingguai/p/9484281.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!