最近在开发一个电商平台的时候,经常会遇到要判断表中是否存在某条记录,不存在,则插入。

判断记录是否存在的sql,不同的写法,也会有不同的性能。

select count(*) from tablename where col = 'col';
select count(*) from tablename where col = 'col';

这种方法性能上有些浪费,没必要把全部记录查出来。

select 1 from tablename where col = 'col' limit 1;
select 1 from tablename where col = 'col' limit 1;

执行这条sql语句,所影响的行数不是0就是1。

特别解释下limit 1,mysql在找到一条记录后就不会往下继续找了。性能提升很多。

结论:推荐第二种方式。