zoukankan      html  css  js  c++  java
  • SQL中存在两个max条件的查询语句

      前段时间找工作参加笔试,笔试题中有一道sql查询语句,条件是两个字段都是最大值,第一直觉是两个字段(例如age、hight)都等于max(),用一个行子查询就行了。第二直觉又不是,如果表中恰好有一条age=max(age),hight=max(hight)的数据,行子查询是没问题的。但是如果age=max(age)的数据hight!=max(hight)并且hight=max(hight)的数据age=!max(age)呢?那么查出来的结果必然是空。

      我想首先保证age=max(age),在age=max(age)的记录里查询hight=max(hight)的记录,这样应该能满足题意了吧?(后来我在其他地方看的题目好像就是要求第一直觉的那样0.0)然后呢?后面就复杂了,查询语句一层一层的嵌套......最后只是大致的草稿出来了,但是笔试时间到,面试官说算了,笔试题不重要......

      今天又看到这个问题的一个例子(他是用行子查询做的),就把这个问题解决了。

    mysql> create table maxtest(age int,hight int);
    Query OK, 0 rows affected (0.27 sec)
    
    mysql> insert into maxtest values(30,180);
    Query OK, 1 row affected (0.05 sec)
    mysql> insert into maxtest values(30,173);
    Query OK, 1 row affected (0.06 sec)
    mysql> insert into maxtest values(32,193);
    Query OK, 1 row affected (0.06 sec)
    mysql> insert into maxtest values(23,199);
    Query OK, 1 row affected (0.06 sec)
    
    mysql> select * from maxtest;
    +------+-------+
    | age  | hight |
    +------+-------+
    |   30 |   180 |
    |   30 |   173 |
    |   32 |   193 |
    |   23 |   199 |
    +------+-------+
    4 rows in set (0.00 sec)
    
    mysql> select * from maxtest where (age,hight)=(select max(age),max(hight) from maxtest);
    Empty set (0.00 sec)
    
    mysql> select * from maxtest where hight=(select max(hight) from (select * from maxtest where age=(select max(age) from maxtest)) a);
    +------+-------+
    | age  | hight |
    +------+-------+
    |   32 |   193 |
    +------+-------+
    1 row in set (0.00 sec)

      java jdbc查询10000次:useTime=22988、24231

      另外一种写法:

    select * from maxtest where age=(select max(age) from maxtest) and hight=(select max(hight) from (select max(age) from maxtest) a);

      这种写法可能更容易理解一些

      java jdbc查询10000次:useTime=20527、***

  • 相关阅读:
    置换python2.7.13的opcode遇到的一些坑
    不思议迷宫:逆向后的放置play
    Vmware(vmdk)虚拟机到hyperv(vhd)虚拟机转换
    MJRefresh自定义刷新动画
    UIScrollView循环滚动1
    IOS开发中如何实现自动检测更新APP
    ios极光推送快速集成教程
    IOS中程序如何进行推送消息(本地推送,远程推送)2(上)
    IOS中程序如何进行推送消息(本地推送,远程推送)2(下)
    IOS中程序如何进行推送消息(本地推送,远程推送)
  • 原文地址:https://www.cnblogs.com/yuanye007/p/5392828.html
Copyright © 2011-2022 走看看