2012-03-16 17 views
0

我需要從一個表中插入每個重複名稱之一到另一個表中。
僅限重複。如何將單個重名的名稱插入到另一個表中?

下面的查詢列出了所有重複的名稱和數量:

select name, count(name) as cnt 
from my_table 
group by name 
having cnt > 1 
order by name 

我如何可以將每次出現到另一個表中的一個?

更新

我的表是不相同的。 我的新表只具有以下行:

id (auto increment) 
name (varchar) 

回答

3

首先創建表。

然後插入數據到新表:

insert into new_table 
select name, count(name) as cnt 
from my_table 
group by name 
having count(name) > 1 
order by name 

的詳細信息,請參考12.2.5.1. INSERT ... SELECT Syntax

EDITED

您可以指定列名或命令,例如:

insert into new_table (column1, column2) 
select name, count(name) as cnt 
... 

對於你的表,你需要創建另一個字段來存儲cnt

alter table `new_table` add column cnt int; 

insert into new_table (name, cnt) 
select name, count(name) as cnt 
... 
+0

你可以在表名之後指定列名稱,如'(name,name_count)',如果需要的話。 – 2012-03-16 21:21:46

+0

對不起,我忘了說,表格不一樣。我試過指定列,但後來我收到錯誤消息:列計數與第1行的值計數不匹配 – Steven 2012-03-16 21:22:34

+0

@Steven,在回答中解釋 – danihp 2012-03-16 21:25:01

相關問題