我试图找出一行是否存在于一个表中。使用MySQL,是更好的做这样的查询:

SELECT COUNT(*) AS total FROM table1 WHERE ...

然后检查总数是否为非零,或者像这样查询是否更好:

SELECT * FROM table1 WHERE ... LIMIT 1

并检查是否返回了任何行?

在这两个查询中,WHERE子句都使用索引。


当前回答

在我的研究中,我可以发现结果越来越快。

select * from table where condition=value
(1 total, Query took 0.0052 sec)

select exists(select * from table where condition=value)
(1 total, Query took 0.0008 sec)

select count(*) from table where condition=value limit 1) 
(1 total, Query took 0.0007 sec)

select exists(select * from table where condition=value limit 1)
(1 total, Query took 0.0006 sec) 

其他回答

COUNT查询更快,虽然可能不是很明显,但就获得所需的结果而言,两者都应该足够了。

下面是@ChrisThompson回答的一个小例子

例子:

mysql> SELECT * FROM table_1;
+----+--------+
| id | col1   |
+----+--------+
|  1 | foo    |
|  2 | bar    |
|  3 | foobar |
+----+--------+
3 rows in set (0.00 sec)

mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 1);
+--------------------------------------------+
| EXISTS(SELECT 1 FROM table_1 WHERE id = 1) |
+--------------------------------------------+
|                                          1 |
+--------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 9);
+--------------------------------------------+
| EXISTS(SELECT 1 FROM table_1 WHERE id = 9) |
+--------------------------------------------+
|                                          0 |
+--------------------------------------------+
1 row in set (0.00 sec)

使用别名:

mysql> SELECT EXISTS(SELECT 1 FROM table_1 WHERE id = 1) AS mycheck;
+---------+
| mycheck |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

你也可以试试EXISTS:

SELECT EXISTS(SELECT * FROM table1 WHERE ...)

根据文档,你可以选择任何东西。

传统上,EXISTS子查询以SELECT *开头,但也可以这样 以SELECT 5或SELECT column n1或任何东西开始。MySQL 在这样的子查询中忽略SELECT列表,所以没有区别。

我选COUNT(1)。它比COUNT(*)快,因为COUNT(*)测试该行中是否至少有一列是!= NULL。您不需要这样做,特别是因为您已经有了一个条件(WHERE子句)。COUNT(1)测试1的有效性,它总是有效的,并且测试所需的时间要少得多。

在我的研究中,我可以发现结果越来越快。

select * from table where condition=value
(1 total, Query took 0.0052 sec)

select exists(select * from table where condition=value)
(1 total, Query took 0.0008 sec)

select count(*) from table where condition=value limit 1) 
(1 total, Query took 0.0007 sec)

select exists(select * from table where condition=value limit 1)
(1 total, Query took 0.0006 sec)