简体   繁体   English

MySQL最大值 - 时间和频率

[英]MySQL max-value – when and how often

If I have a query like 如果我有一个像这样的查询

SELECT (MAX(b.A)/a.A) AS c
FROM a
INNER JOIN b
ON a.b_id = b.id
GROUP by a.id

does MySQL evaluate the value for "MAX(bA)" for every row or only once? MySQL是为每行评估“MAX(bA)”的值还是仅评估一次?

It's just of interest to me if there is room for performance improvement or not. 如果有提高性能的空间,我会感兴趣。

Thanks! 谢谢!

UPDATE UPDATE

OK let's move on to a real world example: I want to calculate the proportional value of a users likes compared to max-user-likes. 好吧让我们转到一个真实世界的例子:我想计算用户喜欢的比例值与max-user-likes相比。

The query to only read the max value of users.likes (which is indexed) takes 0.0003 仅读取users.likes(已编制索引)的最大值的查询需要0.0003

SELECT MAX(likes) 
FROM users

So I now know the value of max-user-likes, let's say it's 10000 so I could query like this which takes 0.0007s: 所以我现在知道max-user-likes的价值,让我们说它是10000,所以我可以查询这样需要0.0007s:

SELECT (users.likes/10000) AS weight 
FROM posts
INNER JOIN users ON posts.author_id = users.id 

So one would expect to have both queries together to be something like 0.0003 + 0.0007s, but it takes 0.3s: 所以人们会期望两个查询一起成为0.0003 + 0.0007s,但需要0.3s:

SELECT (users.likes/(SELECT MAX(likes) FROM users)) AS weight 
FROM posts
INNER JOIN users ON posts.author_id = users.id 

So something seems still wrong with my database - any suggestions? 所以我的数据库似乎仍有问题 - 任何建议?

Since you have no GROUP BY clause, the result will only have one row and you can't know from which row the value of aA will be. 由于您没有GROUP BY子句,因此结果只有一行,您无法知道aA的值将在哪一行。 The value of MAX(bA) will be only evaluated once. MAX(bA)的值仅评估一次。

When you have a GROUP BY clause, MAX(bA) will be evaluated for every group . 当您有GROUP BY子句时,将为每个评估MAX(bA)

In general, the expression within an aggregation function is evaluated and checked for NULL for each row. 通常,会计算聚合函数中的表达式,并检查每行的NULL。 There certainly can be a optimization for MIN and MAX in case of walking through an index, but I doubt that. 如果走过指数,肯定可以对MINMAX进行优化,但我对此表示怀疑。

BTW, you can easily check this, when you execute MAX(id) on a large table. 顺便说一下,当你在一个大表上执行MAX(id)时,你可以轻松地检查这个。 You will see that the execution time is the same as for COUNT(id) (and might be much more than COUNT(*) depending on the engine). 您将看到执行时间与COUNT(id) (并且可能远远超过COUNT(*)具体取决于引擎)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM