下面是幾種數據庫新建一個與存在的表結構相同的表的方法: DB2數據庫: create table ___tablename___ as( select ___col___ from(select distinct ___col___ from ___tablename___ where ___conditions___ order by ___col___))definition only 表結構,類
下面是幾種數據庫新建一個與存在的表結構相同的表的方法:
DB2數據庫:create table ___tablename___ as(
select ___col___ from(select distinct ___col___ from ___tablename___ where ___conditions___ order by ___col___))definition only
表結構,類似于oracle 的create XX as 語句
插入數據:
insert into ___tablename___ select ___col___ from(select distinct ___col___ from ___tablename___ where ___conditions___ order by ___group___)select ___col___ from ___tablename___ where ___conditions___ order by ___col___)
hsql數據庫:
v1.8 版本
select ___col___ into ___tablename___ from(select distinct ___col___ from ___tablename___ where ___conditions___ order by
v2.x版本
create table ___tablename___ as (
select ___col___ from (select distinct ___col___ from ___tablename___ where ___conditions___ order by ___group___))with data
說明:oracle中可以使用rownum 獲得行數 DB2中:ROW_NUMBER()OVER(); hsql特殊,2.0版本前的沒有rownum類似的函數,2.0開始支持rownum()函數
hsql遇到問題:
問題1:
hsqldb1.8版本沒有類似 oracle rownum這樣的函數
hsql1.8想要根據已知的表新建一張表
執行類似這樣的sql語句
SELECT rownum() AS ID___COL___ INTO ___TABLENAME___ FROM(SELECT distinct ___COL___ FROM ___TABLENAME___ WHERE ___CONDITIONS___
ORDER BY ___col___)
報錯,rownum()識別不了,想用返回的行數作為新表的id,但是hsqldb1.8中沒有 類似rownum的函數
所以自己想了一個方法 ,將上面 的sql拆成兩句:
select ___col___ into ___tablename___ from(select distinct ___col___ from ___tablename___ where ___conditions___ order by ___col___)
alter table ___tablename___ add column id integer generated by default as identity(start with 1)
分析一下就是建好表之后再增加id這個字段,并且設置為自增。
問題2:
連接查詢的時候 select table.col as newCol.....
newCol與連接的表中字段名字相同的時候無法查處結果。
如果想利用查出的結果新建表的話,newCol可以先起一個臨時的名字
SELECT table.col as newCol_temp INTO ___TABLENAME___ FROM ___TABLENAME___ WHERE ___CONDITIONS___ GROUP BY ___col___
建好表之后再將字段重命名自己需要的名字:
ALTER TABLE ___TABLENAME___ ALTER COLUMN ___COLNAME___ RENAME TO ___NEWCOLName___
未完。。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com