数据库distinct、union、exists等技术总结
来源:互联网 发布:软件功能拓扑图 编辑:程序博客网 时间:2024/05/22 04:37
一、mysql distinct技术点
1. 创建table:
createtable t1 (id varchar, name varchar);
2. 插入数据:
insertinto t1 values(1,a);
insertinto t1 values(2,b);
insertinto t1 values(3,c);
insertinto t1 values(4,c);
insertinto t1 values(5,b);
3. 查询不重复name:
select distinct name from t1,得到a、b、c
4. 查询name和id字段:
select distinct name,id from t1,得到全部数据
即,只有当name和id都相同时,重复的记录才被排除
5. 将distinct放在id后:
select id, distinct name from table,结果报错!
6. 得到name不重复的每条记录:
select *,count(distinct name) from t1 groupby name
二、union union all distinct技术点
1. union合并后再进行distinct
2. union all合并后不进行distinct
3. (a)union = union all + distinct,(b) union != distinct + union all
4. 对于3的理解(a)和(b)的不同在于执行顺序
5. 只有当数据量级小的时候(如千条以下),没有明显的查询效率;当数据量级大时,应采用临时表merge策略替换union,用exists替换distinct
三、用EXISTS替换DISTINCT技术点
1. 示例:
SELECT DISTINCT DEPT_NO,DEPT_NAME FROM DEPT D , EMP E WHERED.DEPT_NO = E.DEPT_NO; 低效
SELECT DEPT_NO,DEPT_NAME FROM DEPT D WHERE EXISTS ( SELECT ‘X' FROMEMP E WHERE E.DEPT_NO = D.DEPT_NO); 高效
SELECT DEPT_NO,DEPT_NAME FROM DEPT, (SELECT DISTINCT DEPT_NO FROMEMP) TMP WHERE DEPT.DEPT_NO=TMP.DEPT_NO; 避免使用
2. 解析:
当提交一个包含一对多表信息(比如部门表和雇员表)的查询时,避免在SELECT子句中使用DISTINCT. 一般可以考虑用EXIST替换, EXISTS 使查询更为迅速,因为RDBMS核心模块将在子查询的条件一旦满足后,立刻返回结果。
用EXISTS的确可以替代DISTINCT,不过以上方案仅适合DEPT_NO为唯一主键的情况。
3. 参考,如果要去掉重复记录,需参照以下方法:
SELECT * FROM EMP WHERE DEPT_NO EXISTS(select Max(DEPT_NO) FROM DEPTD , EMP E WHERE E.DEPT_NO = D.DEPT_NO GROUP BY D.DEPT_NO)
四、IN和EXISTS效率技术点
表A(小表),表B(大表)
select * from B where cc in (select cc fromA)
这个语句中是先从A表中把cc找出来,然后根据cc再在B中去找相关的cc 由于A表的cc远小于B表的cc 所以可以节省时间。
select * from B exists (select cc from Awhere cc=B.cc)
这句话是先从B表里把cc找出来 然后再在A表里找相关的cc 由于B表的cc远多于A表的cc 所以这样做很浪费时间。
总结: 外大内小用IN,外小内大用EXISTS
数据库distinct、union、exists等技术总结文档 下载
- 数据库distinct、union、exists等技术总结
- exists & distinct
- exists versus distinct
- 用exists代替distinct
- distinct union contact
- union 默认为distinct
- union,union all 等
- 数据库sql语句的exists总结
- 数据库检索中,使用exists时,还是配合distinct 来得快。
- union和distinct 的使用
- linq union 抛出distinct异常
- 使用exists+使用exists代替in+使用exists代替distinct
- UNION与EXISTS简单用法
- 使用exists(Semi-Join)优化distinct语句
- SQL的having,distinct,exists用法介绍
- union总结
- union总结
- Linq Set Operator (Distinct,Intersect,Union,Expect)
- ros
- 你在博客收录集吗?
- TortoiseSVN实现项目管理
- Perl HASH数组
- TortoiseSVN中Branching和Merging实践
- 数据库distinct、union、exists等技术总结
- java多线程顺序打印ABC
- perl 文件[一]
- 动态规划之简单递推(HDU2041,HDU2044,HDU2045,HDU2046,HDU2047)
- C++笔记, 多态虚函数
- 常用正则表达式
- Nginx下实现pathinfo及ThinkPHP的URL Rewrite模式支持
- 【Android界面实现】使用ScrollingTabsView实现有滑动标签的ViewPager效果
- 学习笔记:图像基本知识