使用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;

效果圖如下:

上面兩種方式都可以達到我們的目的,但是推薦使用方案一,原因就在於簡單快捷。

本篇文章如有幫助到您,請給「翎野君」點個贊,感謝您的支持。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM