我正在尝试找出表中是否存在一行。使用 MySQL,做这样的查询是否更好:
SELECT COUNT(*) AS total FROM table1 WHERE ...
并检查总数是否为非零,或者执行如下查询是否更好:
SELECT * FROM table1 WHERE ... LIMIT 1
并检查是否返回了任何行?
在这两个查询中,WHERE 子句都使用索引。
最佳答案
你也可以试试EXISTS
:
SELECT EXISTS(SELECT * FROM table1 WHERE ...)
根据 the documentation ,你可以SELECT
任何东西。
Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.
https://stackoverflow.com/questions/1676551/