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

最想检查一行是否存在,请使用count()

select count(1) from yourTableName where yourCondition;

让我们首先创建一个表:

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20)
);

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

mysql> insert into DemoTable values(100,'Larry');
mysql> insert into DemoTable values(110,'Sam');
mysql> insert into DemoTable values(120,'Mike');
mysql> insert into DemoTable values(130,'Carol');
mysql> insert into DemoTable values(140,'David');

以下是使用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.