sql腳本升級即從一個老的腳本升級到一個新的全量的腳本。比如公司有某一個項目,有的客戶已經用這個項目了,數據庫里面去掉以前的初始化數據外,現在還有了客戶自己的數據。但是這個版本中有嚴重的bug,所以為了讓最新的war包適配以前數據庫,必須對以前的數據庫進行升級。在這里腳本升級以mysql腳本升級到mysql腳本(mysql升級到oracle,oracle升級到mysql這里沒有考慮)
在升級腳本的過程中我們的已知條件是:以前老版本的初始化腳本(包括創建表,初始化數據)這里用A表示,還有新版本的初始化腳本(包括創建表,初始化數據)這里用B表示。所以升級腳本(B-A)
我們已知B-A的內容可能有新增了的一些表,一些索引,一些視圖等等。還有多了很多初始化數據。
如果我們直接用肉眼未免太慢,也不保險。
所以必須通過其他方式解決。
第一步:看新腳本中比老腳本中多了哪些表,哪些索引:
sql語句是:其中TABLE_SCHEMA='A'或者TABLE_SCHEMA='B'就是我們常講的數據庫名。這個sql檢查的是A庫中比B庫中多的表。
select * from (select table_name from information_schema.`TABLES` where TABLE_SCHEMA='A') a where a.table_name not in (select table_name from information_schema.`TABLES` where TABLE_SCHEMA='B');
select * from (select index_name from information_schema.STATISTICS where TABLE_SCHEMA='B') a where a.index_name not in (select index_name from information_schema.STATISTICS where TABLE_SCHEMA='B');
第二步是看新腳本中的表結構是否改變,也就是是否在一個表中增加了一列,或者減少了一列,或者某列的數據類型和長度改變了。
查詢數據庫A的每張表中的列數
設A=select a.table_name,count(a.column_name) column_count from information_schema.columns a
where table_schema = 'A'
group by a.table_name order by a.table_name;
查詢數據庫B的每張表中的列數
設B:select a.table_name,count(a.column_name) column_count from information_schema.columns a
where table_schema = 'A'
group by a.table_name order by a.table_name;
則查詢的語句是:
select * from A LEFT JOIN B on A.table_name=B.table_name;
把上面的A和B代入得到總的sql語句,sql語句如下所示:
select * from (select a.table_name,count(a.column_name) column_count from information_schema.columns a
where table_schema = 'thailand'
group by a.table_name order by a.table_name) A LEFT JOIN (select a.table_name,count(a.column_name) column_count from information_schema.columns a
where table_schema = 'thailand'
group by a.table_name order by a.table_name) B on A.table_name=B.table_name;
查詢的結果如下圖所示:
通過這兩個sql語句,可以為我們升級腳本減少一些時間。