mysql创建表时设置最大值_如何在mysql表中选择最大值行

bd96500e110b49cbb3cd949968f18be7.png

I have the following table

Table structure:

CREATE TABLE IF NOT EXISTS `people` (

`name` varchar(10) NOT NULL,

`age` smallint(5) unsigned NOT NULL,

PRIMARY KEY (`name`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert some values:

INSERT INTO `people` (`name`, `age`) VALUES

('bob', 13),

('john', 25),

('steve', 8),

('sue', 13);

Executed Query:

SELECT MAX( `age` ) , `name` FROM `people` WHERE 1

Expected Result:

25, John

Generated Result

25, bob

We can achieve this by using this query

SELECT `age`, `name` FROM `people` ORDER BY age DESC LIMIT 1

Question 1 : What I made mistake here and why this MAX function is not return the relevant row information?

Question 2: Which one is good to use, to increase performance MAX function or ORDER BY clause?

解决方案Question 1 : What I made mistake here and why this MAX function is not return the relevant row information?

You need to read up on the group by clause.

MySQL is being a lot more permissive than it should, introducing confusion in the process. Basically, any column without an aggregate should be included in the group by clause. But MySQL syntactic sugar allows to "forget" columns. When you do, MySQL spits out an arbitrary value from the set that it's grouping by. In your case, the first row in the set is bob, so it returns that.

Question 2: Which one is good to use, to increase performance MAX function or ORDER BY clause?

Your first statement (using max() without a group by) is simply incorrect.

If you want one of the oldest users, order by age desc limit 1 is the correct way to proceed.

If you want all of the oldest users, you need a subselect:

SELECT p.* FROM people p WHERE p.age = (select max(subp.age) from people subp);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值