当可以使用GROUP BY时,为什么不使用DISTINCT? [英] Why shouldn’t you use DISTINCT when you could use GROUP BY?

查看:763
本文介绍了当可以使用GROUP BY时,为什么不使用DISTINCT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据MySQL性能Wiki的提示:

According to tips from MySQL performance wiki:

在有或可以使用GROUP BY时不要使用DISTINCT.

Don't use DISTINCT when you have or could use GROUP BY.

有人可以发布可以使用GROUP BY代替DISTINCT的查询示例吗?

Can somebody post example of queries where GROUP BY can be used instead of DISTINCT?

推荐答案

如果您知道结果中的两列始终直接相关,则这样做会比较慢:

If you know that two columns from your result are always directly related then it's slower to do this:

SELECT DISTINCT CustomerId, CustomerName FROM (...)

比这个:

SELECT CustomerId, CustomerName FROM (...) GROUP BY CustomerId

因为在第二种情况下,它只需要比较id,但是在第一种情况下,它必须比较两个字段.这是MySQL特有的技巧.它不适用于其他数据库.

because in the second case it only has to compare the id, but in the first case it has to compare both fields. This is a MySQL specific trick. It won't work with other databases.

这篇关于当可以使用GROUP BY时,为什么不使用DISTINCT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆