SQL:使用替换字更新表中的行

时间:2014-11-17 20:17:46

标签: mysql

我有这样的表: -

ID               Name                 Email                 UserName
1               Johen mak         jojo@yahoo.com
2               jameel mak        jojo@gmail.com
3               gawil gorgy       jojo@homail.com
4               mak jor           gop@yahoo.com

现在我需要从UserName列插入Email值,但不需要@yahoo.com@gmail.com ....

但如果有双重UserName。必须添加_1_2 ...

但是如果任何用户都有英语UserName,我们就不能更改,只有在UserName不是英语的情况下才能更改和更新。 所以该表必须如下: -

ID               Name                 Email                 UserName
1               Johen mak         jojo@yahoo.com              jojo
2               jameel mak        jojo@gmail.com              jojo_1
3               gawil gorgy       jojo@homail.com             jojo_2
4               mak jor           gop@yahoo.com               gop

我怎么能这样做!

2 个答案:

答案 0 :(得分:0)

这是SQL-SERVER语法, EnglishNames只是一个有名字的表,你必须从某个地方填写它。

DECLARE @users TABLE 
( 
    id INT, 
    name VARCHAR(32),
    email VARCHAR(32),
    username VARCHAR(32)
)
INSERT INTO @users
select ROW_NUMBER() OVER(ORDER BY Name) AS Id, Name, Email, substring(Email, 0, charindex('@', Email)) AS UserName
from Users

update @users set username = 
case 
    when (select count(*) from EnglishNames e where e.Name = username) > 0 then username + '_' + CAST(id AS VARCHAR(10))
    when (select count(*) from EnglishNames e where e.Name = username) = 0 then username
    end
where
id not in (
select min(id) from @users
group by username
)

select * from @users

答案 1 :(得分:0)

这是非英文名称:

set @rownum := 1;
SELECT U.Email,P.total_perfix,if(P.total_perfix > 1 ,  
CONCAT(P.perfix,'_', mod(@rownum:=@rownum+1,P.total_perfix)),P.perfix) as new_username
FROM USER_TABLE U , ( SELECT count(*) as total_perfix, 
SUBSTRING(Email, 1, INSTR(Email, '@') - 1)
                           AS perfix
                   FROM USER_TABLE group by perfix) P 
WHERE SUBSTRING(U.Email, 1, INSTR(U.Email, '@') - 1) = p.perfix 
AND u.name NOT REGEXP '^[A-Za-z0-9 ]+$';

如果您只删除最后一行,您将拥有所有[英语和非英语]

AND u.name NOT REGEXP '^[A-Za-z0-9 ]+$';

这里是Demo