Best way to test if a row exists in a MySQL table(测试 MySQL 表中是否存在行的最佳方法)
问题描述
我试图找出表中是否存在一行.使用 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 表中是否存在行的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试 MySQL 表中是否存在行的最佳方法


基础教程推荐
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01