Mysql对比两张数据表,得到差异的记录

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/jacken123456/article/details/84337847

我们在涉及到数据库相关的的软件开发中,经常会对比两张数据表,得到它们之间的差集。

下面是对应的SQL语句:

//table1(%1)中有,table2(%2)中没有的数据
//cmd = QString("select orderid from %1 where not exists (select * from %2 where %1.orderid = %2.orderid)").arg(table1,table2);
//table2(%1)中有,table1(%2)中没有的数据
cmd = QString("select orderid from %1 where not exists (select * from %2 where %1.orderid = %2.orderid)").arg(table2,table1);

在查询到差集后,也可以把结果保存到变量当中,方便进行其它的操作。

在把大量数据插入到数据库中时,我们不可能一条一条的插入,这样的话速度就会很慢,这时,我们一般会批量的插入数据,经过测试,6万条数据只需要7s左右的时间。批量插入的代码如下:

QSqlQuery query;
QSqlDatabase::database().transaction();	 	//开始启动事务
query.prepare("insert into t_student_info(user_id,card_id,action) values(?,?,?)");
query.addBindValue(m_userid);
query.addBindValue(m_card_id);
query.addBindValue(m_action);
if(!query.execBatch())
{
	qDebug()<<query.lastError();
}
QSqlDatabase::database().commit();

批量插入时,遇到重复的数据一般会执行失败,程序结束,导致后面不重复的数据也插入失败,这种情况,一般可以使用:

query.prepare("insert ignore into t_student_info(user_id,card_id,action) values(?,?,?)");

这句SQL语句来替换insert into。当插入数据时,如重复数据,将不返回错误,只以警告形式返回。

猜你喜欢

转载自blog.csdn.net/jacken123456/article/details/84337847