文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>如何刪除在 Table 內重複的資料列 ?

如何刪除在 Table 內重複的資料列 ?

时间:2007-04-30  来源:cxm.cm

有時候表格內發生了重複的資料列,造成 PK 或者 Unique key 無法建立,在大量的表格內要找出發生違反 constraint 的 data row ,可以使用下列的程序發現,再給予刪除後即可以重新建立 constraint 。

Example:

Table name: test

SQL> select * from test;

<IFRAME name=google_ads_frame marginWidth=0 marginHeight=0 src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-4093929403795683&amp;dt=1177904923906&amp;lmt=1176216700&amp;format=250x250_as&amp;output=html&amp;channel=4478728948&amp;url=http%3A%2F%2Fwww.odba.idv.tw%2Fduprow.htm&amp;color_bg=FFFFFF&amp;color_text=000000&amp;color_link=003366&amp;color_url=CC0000&amp;color_border=FFFFFF&amp;ad_type=text_image&amp;ref=http%3A%2F%2Fwww.google.cn%2Fsearch%3Fcomplete%3D1%26hl%3Dzh-CN%26newwindow%3D1%26q%3Dora-02437%26meta%3Dlr%253Dlang_zh-CN%257Clang_zh-TW&amp;flash=9&amp;u_h=768&amp;u_w=1024&amp;u_ah=740&amp;u_aw=1024&amp;u_cd=16&amp;u_tz=480&amp;u_java=true" frameBorder=0 width=250 scrolling=no height=250 allowTransparency></IFRAME>

ID ID1 ID2

---------- ---------- ----------

1 2 3

1 2 5

1 7 5

1 7 5

7 7 5

妳可以發現重複了一筆資料 (1,7,5) ,如果我們要在 (ID,ID1,ID2 上建立 PK OR UNIQUE CONSTRAINT ,必須先做個資料清潔動作 )

1 確認表格內是否有重複的資料列

SQL> select id,id1,id2,count(*) from test group by id,id1,id2 having count(*) > 1;

ID ID1 ID2 COUNT(*)

---------- ---------- ---------- ----------

1 7 5 2

(1,7,5) 出現了兩筆重複的資料

2 保守起見,先建立一個 EXCEPTION TABLE 來儲存重複的 ROW

SQL>$?/rdbms/admin/utlexcpt

以建立表格

SQL> alter table test add constraint test_pk primary key (id ,id1,id2)

2 exceptions into exceptions;

alter table test add constraint test_pk primary key (id ,id1,id2)

*

ERROR 在行 1:

ORA-02437: 無法驗證 (SYS.TEST_PK) - 主索引鍵違規

SQL> select count(*) from exceptions;

COUNT(*)

----------

2

有兩筆重複資料列。

3 直接刪除重複的資料列

SQL> delete from test where rowid not in (select min(rowid) from test group by id,id1,id2);

已刪除 1 個資料列 .

SQL> select * from test;

ID ID1 ID2 ENAME

---------- ---------- ---------- ----------

1 2 3 tom

1 2 5 tom

1 7 5 tom

7 7 5 tom

SQL> commit;

確認完成 .

提高刪除速度的方法 ( 小技巧 )

delete from test where rowid in (select rowid from test minus select min(rowid) from test group by id,id1,id2 );
相关阅读 更多 +
排行榜 更多 +
星宇驾考

星宇驾考

学习教育 下载
我快递

我快递

音乐节奏 下载
减速射手

减速射手

飞行射击 下载