我想知道这两个查询之间是否存在性能差异,检查是否存在记录?
select count(1) from table where id = 1;
或
select id from table where id = 1;
答案 0 :(得分:3)
我不认为这两个查询之间会有太大差异:第二种情况下选择字段(它是索引的一部分),并计算第一种情况中的一行...这有很大的不同。
然而,出于好奇,我在计算机上的数据库上对这些查询进行了非常快速的基准测试 - 注意邮政表中只有7行,所以可能不是接近真实情况,但由于id
上存在PK,这意味着索引...... 。
这是我得到的:
mysql> select benchmark(10000000000, 'select sql_no_cache id from post where id = 1');
+-------------------------------------------------------------------------+
| benchmark(10000000000, 'select sql_no_cache id from post where id = 1') |
+-------------------------------------------------------------------------+
| 0 |
+-------------------------------------------------------------------------+
1 row in set (1 min 0,25 sec)
mysql> select benchmark(10000000000, 'select sql_no_cache count(1) from post where id = 1');
+-------------------------------------------------------------------------------+
| benchmark(10000000000, 'select sql_no_cache count(1) from post where id = 1') |
+-------------------------------------------------------------------------------+
| 0 |
+-------------------------------------------------------------------------------+
1 row in set (1 min 0,23 sec)
所以,真的没那么大的区别,似乎是^^
答案 1 :(得分:1)
虽然Pascal在他的简历中是正确的,但他的例子是错误的。
benchmark(10000000000, 'select sql_no_cache id from post where id = 1')
上述语句使用语句评估字符串,而不是SELECT语句本身。 BENCHMARK 函数的正确语法为:
benchmark(10000000000, (select sql_no_cache id from post where id = 1))
此外,至少在MySQL 5.5.22中,在提供给BENCHMARK的语句中使用SQL_NO_CACHE会导致错误:
mysql> SELECT BENCHMARK(1000000000,(SELECT SQL_NO_CACHE COUNT(1) FROM players WHERE id=1));
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'COUNT(1) FROM players WHERE id=1))' at line 1
mysql> SELECT BENCHMARK(1000000000,(SELECT SQL_NO_CACHE id FROM players WHERE id=1));
ERROR 1054 (42S22): Unknown column 'SQL_NO_CACHE' in 'field list'
但是,实际语句,40000记录表和查询缓存关闭的实验确认COUNT的工作速度比检索ID要快一些,即使差异可能被忽略不计。
mysql> set query_cache_type=0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT SQL_NO_CACHE benchmark(1000000000,(SELECT id FROM test WHERE id=1));
+-----------------------------------------------------------+
| benchmark(1000000000,(SELECT id FROM players WHERE id=1)) |
+-----------------------------------------------------------+
| 0 |
+-----------------------------------------------------------+
1 row in set (23.17 sec)
mysql> SELECT SQL_NO_CACHE benchmark(1000000000,(SELECT COUNT(1) FROM test WHERE id=1));
+-----------------------------------------------------------------+
| benchmark(1000000000,(SELECT COUNT(1) FROM players WHERE id=1)) |
+-----------------------------------------------------------------+
| 0 |
+-----------------------------------------------------------------+
1 row in set (22.50 sec)
答案 2 :(得分:0)
第二个声明可能更快。但出于实际目的,差异可以忽略不计