使用Mysql中的concat函数或正则匹配来快速批量生成用于执行的sql语句

背景介绍

今天需要给一张表里面补数据,需要按照行的维度进行update,如果是个别数据那么直接写update语句就可以了,但是场景要求的是将整表的数据进行update,要实现这个需求就不能只靠蛮力了,需要有一点小技巧来完成这个工作。

实例演示

以下面的场景作为示例进行讲解:

学生表:

一张简单的学生表,其中记录了学生ID、名称、班级ID

借阅表:

一张简单的借阅表,当中记录了借阅的书籍和对应借阅学生ID,但是每行中的学生名称和班级ID是空的。

目标:快速生成update语句将book_borrow表中的student_name和class_id更新为正确的数据。

思路:

对于update操作,我们需要写出来一个这样的update语句,

update book_borrow set student_name = ?, class_id = ? where id = ?;

把update需要用的变量全部使用select查询出来。即,根据book_borrow表中的student_id,去student表中查出name和class_id。

select a.id,b.`name`,b.class_id from book_borrow a inner join student b on a.student_id = b.id;

 两种解决方案

 方案一:使用Mysql中的concat函数

对于concat函数,如果有不清楚的话建议阅读这篇文章 https://www.w3resource.com/mysql/string-functions/mysql-concat-function.php

上面我们查到了update语句中所有需要用到的变量。即,借阅ID、学生名称、班级ID,那么下一步我们只需要通过concat函数进行字符串拼接就可以了。

select concat("update book_borrow set student_name = '",b.`name`,"', class_id = ",b.class_id," where id = ",a.id,";") from book_borrow a inner join student b on a.student_id = b.id;

执行之后便是我们想要的结果了,如下图所示:

最后我们把sql拷出来直接执行就可以了。

方案二:使用正则表达完成匹配功能

select concat("update book_borrow set student_name = '",b.`name`,"', class_id = ",b.class_id," where id = ",a.id,";") from book_borrow a inner join student b on a.student_id = b.id;

将上面查询到的结果放到文本编辑器中,然后使用正则表达式来进行填充

正则表达式见下:

Find:(.*) (.*) (.*)

Replace:update book_borrow set student_name = '2', class_id = 3 where id = 1;

效果图如下:

上面两种方式都可以达到我们的目的,但是推荐使用方案一,原因就在于简单快捷。

本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

原文地址:https://www.cnblogs.com/lingyejun/p/11915413.html