2014-01-15 56 views
0

重命名重複行我有一個表像下concating在MySQL

ID student_name  dept  email 

1 Mary Wise   Eng   [email protected] 
2 John Walter   Sc   [email protected] 
3 Sophia Jacob  Politics [email protected] 
4 Ava William   Eng   [email protected] 
5 Mary Wise   Politics [email protected] 
6 John Walter   Eng   [email protected] 
7 John Walter   Politics [email protected] 
8 Sophia    Eng   [email protected] 
9 Emma    Eng   [email protected] 
10 Sherlock   Eng   [email protected] 

生成的電子郵件ID山坳通過[email protected] 問題是當名稱是相同的電子郵件ID也是相同。 我想要電子郵件ID附加1,2,3時存在相同的名稱。

For example in table above 
the mary-wise on 5th row should be [email protected], 
6th row should be, [email protected], 
7th row should be, [email protected] 

如何儘可能快地使用mysql查詢更新我的電子郵件列。 我嘗試使用php與MySQL它需要太長,當表中包含百萬行。

感謝

回答

0

下面的SQL將枚舉重複:使用join

select t.*, 
     @rn := if(@StudentName = StudentName, 1, @rn + 1) as seqnum, 
     @StudentName := StudentName 
from table t cross join 
    (select @rn := 0, @StudentName := '') const 
order by StudentName; 

你可以把這個在update

update t join 
     (select t.*, 
      @rn := if(@StudentName = StudentName, 1, @rn + 1) as seqnum, 
      @StudentName := StudentName 
     from table t cross join 
      (select @rn := 0, @StudentName := '') const 
     order by StudentName 
     ) toupdate 
     on t.name = toupdate.name and toupdate.seqnum > 1 
    set email = concat(replace(t.StudentName, ' ', '-'), toupdate.seqnum - 1, '@xxx.cc); 
+0

電子郵件中,我希望更新的值,其中列名它有超過1個相同的條目。連續的條目應該添加1,2,3等 – user3197800

+0

@ user3197800。 。 。這就是'update'所做的。 –

0

我認爲這是更好地爲您做出email列是唯一的,並使用ON DUPLICATE KEY UPDATE語法(更多here)。

您仍然需要跟蹤要附加到新值的數字。爲此,您可以創建一個帶有自動增量字段的獨立表格,並從中獲取新值。

+0

我無法讓它變得獨一無二,因爲您在我的問題中看到的值可以提供給我。現在我的工作是通過根據該電子郵件的發生次數添加1,2,3等來使其獨特。 – user3197800

+0

您可以使用唯一的'email'字段和原始ID創建臨時表,使用'ON DUPLICATE KEY UPDATE'在主表中逐個插入記錄,然後使用原始ID字段使用新值更新主表。 –

0

,如果你有CTE(如果你也許可以切換到Postgres的9),這將是很容易實現:

SELECT 
id 
, student_name 
, concat(
    replace(lower(student_name), ' ', '-') 
    , case 
    when cnt > 1 then numb 
    end 
    ,'@xxx.cc' 
) as newmail 
FROM (
SELECT 
count(*) over (partition BY student_name) as cnt 
, count(*) over (partition BY student_name order by id) as numb 
, id 
, student_name 
FROM tab1 
order by id 
) subq 

sqlFiddle demo