测试MySQL表中是否存在行的最佳方法 [英] Best way to test if a row exists in a MySQL table
问题描述
我试图找出表中是否存在一行.使用MySQL,最好执行如下查询:
I'm trying to find out if a row exists in a table. Using MySQL, is it better to do a query like this:
SELECT COUNT(*) AS total FROM table1 WHERE ...
并检查总数是否为非零或执行以下查询是否更好:
and check to see if the total is non-zero or is it better to do a query like this:
SELECT * FROM table1 WHERE ... LIMIT 1
并检查是否返回了任何行?
and check to see if any rows were returned?
在两个查询中,WHERE子句均使用索引.
In both queries, the WHERE clause uses an index.
推荐答案
您也可以尝试EXISTS
:
SELECT EXISTS(SELECT * FROM table1 WHERE ...)
,并按照文档,您可以SELECT
任何内容.
and per the documentation, you can SELECT
anything.
传统上,EXISTS子查询以SELECT *开头,但是它可以 以SELECT 5或SELECT column1或其他任何内容开头. MySQL 忽略此类子查询中的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.
这篇关于测试MySQL表中是否存在行的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!