mysql中有没有依据某一列当这存在这个数据存在的时候不插入,不存在则插入。这一列不是唯一索引和主键。
列如:ttid ooid title
1 1 a
1 2
1 3
2 4
2 5
2 6
现在我有一条数据ttid=1,ooid=7 title=b,因为ttid=1在数据库中已经存在所以这条记录不插入
mysql中有没有依据某一列当这存在这个数据存在的时候不插入,不存在则插入。这一列不是唯一索引和主键。
列如:ttid ooid title
1 1 a
1 2
1 3
2 4
2 5
2 6
现在我有一条数据ttid=1,ooid=7 title=b,因为ttid=1在数据库中已经存在所以这条记录不插入
如果非要用SQL实现,可以这么写:
insert into table(ttid,ooid,title)
select 1,7,'b' from table where not exists(select ttid from table where ttid=1) limit 1
但是建议还是先查一下结果为0的话再插入好一点,除非是你这个操作很频繁,n次操作会带来2n次数据库连接,数据库压力比较大那就用SQL。
假设没有其他异常,我的做法是
int count = dao.update(...);//where conditions
if(count == 1) {
// we have updated one record
} else {
// do insert
}
如果存在原来的记录的话,这里只做一次更新操作;
如果不存在就做一个尝试更新的操作和一次插入的操作。
4 回答1.2k 阅读✓ 已解决
8 回答1.2k 阅读
3 回答1k 阅读✓ 已解决
2 回答1.7k 阅读
2 回答1.2k 阅读
1 回答856 阅读✓ 已解决
1 回答649 阅读✓ 已解决
我的话我会先select下,看看有没有,如果num==0我就插入