检查 MySQL 表中某行是否存在的最有效方法是什么?
mysqlmysqli database
想要检查某行是否存在的最有效方法是使用 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.