有一张表UserInfo,
字段(UserNo 用户编号,UserName 用户名,UserAge 用户年龄,UserSalary 用户薪水)
这张表存储了100万左右的数据,
请用一条你认为最高效的sql实现以下条件数据条数的统计。
1. UserSalary >9999 and UserAge >35
2. UserSalary >9999 and UserAge <35
3. UserSalary <9999 and UserAge >35
4. UserSalary <9999 and UserAge <35 遇到的这个面试题,也不知道标准答案,大家有什么好的办法呢?

解决方案 »

  1.   

    貌似很简单,又貌似有陷阱。建索引的问题要看数据量、查询的数据集大小、数据分布等等。而且你问的是“sql写法”,貌似答案只有一种...select count(主键) from tb where 
      

  2.   

    在UserAge属性上建立索引,然后查询条件结构为UserAge在最外层,UserSalary嵌套在最里面一层。
      

  3.   

    单纯SQL单表查询,貌似没啥好优化的
      

  4.   


    我认为他想考你union 和 union all会不会用。我以前民曾经遇到别人这么考我,那时我不会select COUNT(用户编号) as count1 from UserInfo where UserSalary >9999 and UserAge >35
    union all select COUNT(用户编号) as count2 from UserInfo where UserSalary >9999 and UserAge <35
    union all select COUNT(用户编号) as count3 from UserInfo where UserSalary <9999 and UserAge >35
    union all select COUNT(用户编号) as count4 from UserInfo where UserSalary <9999 and UserAge <35
      

  5.   

    看起来是有点蛋疼……是个坑吧?写过sql应该都能写出来又没有说需要对这个进行优化——他么有给其他条件嘛……
      

  6.   

    Case When是正道
    这个条件涵盖所有,所以索引只要有这两个字段的就OK了(索引扫描)
      

  7.   

    select sum(case when UserSalary >9999 and UserAge >35 then 1 else 0 end ) as count1,
      sum(case when UserSalary >9999 and UserAge <35 then 1 else 0 end ) as count2,
      sum(case when UserSalary <9999 and UserAge >35 then 1 else 0 end ) as count3,
      sum(case when UserSalary <9999 and UserAge <35 then 1 else 0 end ) as count4
       from UserInfo 
      

  8.   

    如果要最高效的sql实现,可以用视图索引.