在 SQL 中,是否有其他方法可以在添加记录之前查看记录是否已经存在? [英] In SQL, is there an alternative way to see if a record is already there before adding it?

查看:38
本文介绍了在 SQL 中,是否有其他方法可以在添加记录之前查看记录是否已经存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 MySQL 表,

I have a MySQL table like this,

id (primary key) | name | scores

我正在读取一个大文件以将记录插入到 MySQL 表中.

and I am reading a large file to insert records into the MySQL table.

新的记录会被添加到这个文件中,但旧的记录不会被删除,所以当我读取文件时,数据库中已经有很多记录了.

New records will be added into this file but the old records are not deleted, so when I read the file, a lot of records are already in the database.

除了使用 SELECT COUNT 查看一条记录是否已经在数据库中之外,有没有最好的方法来检查它(以节省处理时间和数据库负载)?

Except to use SELECT COUNT to see if a record is already in the database, is there a best way to check it (to save processing time & database load)?

或者我应该直接插入它?(无论如何,数据库将不允许具有重复 id 的记录.)

Or maybe I should just INSERT it directly? (The database will not allow records with duplicate id anyway.)

推荐答案

我通常使用 update + insert 方法.

I usually use update + insert method.

首先我将运行更新语句.更新查询就像一个选择查询 + 直接更新数据.

first i will run the update statement. the update query will act like a select query + directly update the data.

update t1 set t1.Name = 'Name', t1.Scores = 99
where t1.Name = 'Name' and t1.Scores = 99

然后检查是否有受上述查询影响的行.如果不运行插入语句

then check if there is a row affected by the above query. if not run the insert statement

if @@RowCount = 0
 insert into t1 (Name, Scores) values ('Name',99)

这篇关于在 SQL 中,是否有其他方法可以在添加记录之前查看记录是否已经存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆