我會爲此在多個步驟。一步完成的大量刪除操作讓我感到非常緊張 - 如果您犯了一個錯誤,該怎麼辦?沒有sql'undo'語句。
-- Setup the data
DROP Table foo;
DROP Table bar;
DROP Table bat;
DROP Table baz;
CREATE TABLE foo (
id int(11) NOT NULL,
SchemeName varchar(50),
SchemeNumber varchar(15),
PRIMARY KEY (id)
);
insert into foo values (714, 'Malcolm', 'ABC123');
insert into foo values (80, 'Malcolm', 'ABC123');
insert into foo values (96, 'Malcolms Scheme', 'ABC123');
insert into foo values (101, 'Malcolms Scheme', 'ABC123');
insert into foo values (98, 'Malcolms Scheme', 'DEF888');
insert into foo values (654, 'Another Scheme ', 'BAR876');
insert into foo values (543, 'Whatever Scheme ', 'KJL111');
-- Find all the records that have dups, find the longest one
create table bar as
select max(length(SchemeName)) as max_length, SchemeNumber
from foo
group by SchemeNumber
having count(*) > 1;
-- Find the one we want to keep
create table bat as
select min(a.id) as id, a.SchemeNumber
from foo a join bar b on a.SchemeNumber = b.SchemeNumber
and length(a.SchemeName) = b.max_length
group by SchemeNumber;
-- Select into this table all the rows to delete
create table baz as
select a.id from foo a join bat b where a.SchemeNumber = b.SchemeNumber
and a.id != b.id;
這會爲您提供一個只包含要刪除的行的記錄的新表。
現在檢查這些,並確保它們只包含要刪除的行。通過這種方式,您可以確保在執行刪除操作時,您確切地知道將會發生什麼。它也應該很快。
然後,當您準備好時,使用此命令使用此命令刪除行。
delete from foo where id in (select id from baz);
這似乎是更多的工作,因爲不同的表,但它更安全,可能與其他方式一樣快。另外,您可以在任何步驟中停止並確保在執行任何實際刪除之前數據是您想要的。
不住那些有回答 - 請看我的更新! – 2010-10-06 17:36:13
您的數據在Jet/ACE或SQL Server中?如果前者,爲什麼你用SQL Server術語給你的數據類型?例如,Jet/ACE不支持BIGINT。數據在SQL Server中的事實將是一個重要的細節,因爲它意味着SQL方言是不同的。或者您正在通過ODBC訪問它,這對選擇最佳任務方式具有各種含義。 – 2010-10-08 02:18:42
它在Access中,是的。抱歉。我更習慣於SQL Server,因此以這種形式提供了數據。我會改變它來說清楚。 – 2010-10-08 08:04:53