如果我有一张桌子
CREATE TABLE users (
id int(10) unsigned NOT NULL auto_increment,
name varchar(255) NOT NULL,
profession varchar(255) NOT NULL,
employer varchar(255) NOT NULL,
PRIMARY KEY (id)
)
我想获得所有专业领域的独特价值,什么会更快(或建议):
SELECT DISTINCT u.profession FROM users u
or
SELECT u.profession FROM users u GROUP BY u.profession
?
下面是一个简单的方法,它将为每个查询打印2个不同的运行时间。
DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;
SET @t1 = GETDATE();
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
SET @t1 = GETDATE();
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
或尝试设置统计时间(Transact-SQL)
SET STATISTICS TIME ON;
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET STATISTICS TIME OFF;
它简单地显示了解析、编译和执行每条语句所需的毫秒数,如下所示:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
经过大量的测试,我们得出的结论是GROUP BY更快
选择sql_no_cache
opnamegroep_intern
从telwerken
WHERE opnemergroep IN (7,8,9,10,11,12,13) group by opnamegroep_intern
总共0.0944秒
显示记录0 - 29(共635条,查询持续0.0484秒)
选择sql_no_cache
不同的(opnamegroep_intern)
从telwerken
WHERE opnemergroep IN (7,8,9,10,11,12,13)
635总共0.2117秒(几乎慢了100%)
韦格弗面包车记录0 - 29(总共635,查询时间0.3468秒)