zoukankan      html  css  js  c++  java
  • SQL子查询分析

    在这里看到了一个帖子 http://www.iteye.com/topic/1122917,很简单,凑下热闹,因为Oracle,SQLServer的子查询和Join算法的选择很多,但是MySQL方面就没有那么多的选择了,所以很多子查询的性能都很差,这里分析几个帖子里MySQL的答案。
    需求:使用SQL语句查出哪些人即会玩basketball又会玩badminton,找出这样的name-hobby组合
    create table test (NAME varchar(20) not null, HOBBY varchar(20) not null);
    insert into  test values('Adam','basketball');
    insert into  test values('Bill','basketball');
    insert into  test values('Bill','football');
    insert into  test values('Cyper','basketball');
    insert into  test values('Cyper','badminton');
    insert into  test values('David','basketball');
    insert into  test values('David','badminton');
    insert into  test values('David','table tennis');
    一个Groupby的写法
    select name,group_concat(hobby),count(*) 
    from test where HOBBY IN ('basketball','badminton')
    group by name having count(*)]]]]>1;
    一个exists的写法
    select * from test a
    WHERE hobby = 'basketball'
    AND EXISTS (SELECT * from TEST b
    WHERE a.nameb.name AND b.hobby = 'badminton');
    但是有重复的情况如何处理?
    insert into test values('Bill','basketball');
    insert into test values('Bill','basketball');
    insert into test values('David','badminton');
    insert into test values('David','badminton');
    Groupby的写法需要进化使用distinct
    select name,group_concat(distinct(hobby)), count(distinct(hobby))
    from test where hobby in ('basketball','badminton') group by name having count(distinct(hobby))>1
    exists的写法的写法不用修改,但是执行计划是DEPENDENT SUBQUERY,这样效率很差,那么要优化成Derived Table写法,如下
    select distinct(a.name) as name,concat(a.hobby, b.hobby) from test a,(SELECT distinct(name) as name , hobby from TEST WHERE hobby = 'badminton') as b
    WHERE a.hobby = 'basketball'
    AND a.name = b.name
    --EOF--

    作者:Buro#79xxd 出处:http://www.cnblogs.com/buro79xxd/ 文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    字符串匹配算法之Rabin-Karp算法
    算法导论之最近顶点对
    php连mssql中文乱码问题
    Trie树
    PAT 1057. Stack (30)
    PAT 1033. To Fill or Not to Fill (25)
    PAT 1034. Head of a Gang (30)
    PAT 1075. PAT Judge (25)
    spring框架资料
    Spring Security资料
  • 原文地址:https://www.cnblogs.com/buro79xxd/p/2658637.html
Copyright © 2011-2022 走看看