mysql max 多个字段_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.27sec)

mysql> insert into maxtest values(30,180);

Query OK,1 row affected (0.05sec)

mysql> insert into maxtest values(30,173);

Query OK,1 row affected (0.06sec)

mysql> insert into maxtest values(32,193);

Query OK,1 row affected (0.06sec)

mysql> insert into maxtest values(23,199);

Query OK,1 row affected (0.06sec)

mysql> select * frommaxtest;+------+-------+

| age | hight |

+------+-------+

| 30 | 180 |

| 30 | 173 |

| 32 | 193 |

| 23 | 199 |

+------+-------+

4 rows in set (0.00sec)

mysql> select * from maxtest where (age,hight)=(select max(age),max(hight) frommaxtest);

Emptyset (0.00sec)

mysql> select * from maxtest where hight=(select max(hight) from (select * from maxtest where age=(select max(age) frommaxtest)) a);+------+-------+

| age | hight |

+------+-------+

| 32 | 193 |

+------+-------+

1 row in set (0.00sec)

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、***

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值