检查 MySQL 表中的行是否存在的最有效方法是什么?


检查行是否存在的最有效方式是使用 count()

select count(1) from yourTableName where yourCondition;

我们首先创建一个表

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.73 sec)

以下是使用 insert 命令在表中插入一些记录的查询

mysql> insert into DemoTable values(100,'Larry');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(110,'Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(120,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(130,'Carol');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(140,'David');
Query OK, 1 row affected (0.12 sec)

以下是使用 select 命令从表中显示记录的查询

mysql> select *from DemoTable;

这将产生以下输出

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 110  | Sam       |
| 120  | Mike      |
| 130  | Carol     |
| 140  | David     |
+------+-----------+
5 rows in set (0.00 sec)

以下是检查表中是否存在行的查询。在此,我们检查 Id = 130 的行

mysql> select count(1) from DemoTable where Id=130;

这将产生以下输出

+----------+
| count(1) |
+----------+
|        1 |
+----------+
1 row in set (0.00 sec)

上面的输出表明存在该行。

NOTE: If you get 1 that means row is present otherwise the row isn’t present.

更新日期:2019-07-30

234 次浏览

开始你的职业生涯

完成课程即可获得认证

开始学习
广告