Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Eindeutigen Benutzernamen aus Vor- und Nachnamen generieren?

CREATE TABLE bar LIKE foo;

INSERT INTO bar (id,user,first,last)
(SELECT f.id,CONCAT(SUBSTRING(f.first,1,1),f.last,
     (SELECT COUNT(*) FROM foo f2
         WHERE SUBSTRING(f2.first,1,1) = SUBSTRING(f.first,1,1)
               AND f2.last = f.last AND f2.id <= f.id
         )),f.first,f.last from foo f);

DROP TABLE foo;
RENAME TABLE bar TO foo;

Dies beruht auf einem Primärschlüssel id , also für jeden in bar eingefügten Datensatz , zählen wir nur in foo gefundene Duplikate mit id kleiner als bar.id .

Gegeben foo:

select * from foo;
+----+------+--------+--------+
| id | user | first  | last   |
+----+------+--------+--------+
|  1 | aaa  | Roger  | Hill   | 
|  2 | bbb  | Sally  | Road   | 
|  3 | ccc  | Fred   | Mount  | 
|  4 | ddd  | Darren | Meadow | 
|  5 | eee  | Sharon | Road   | 
+----+------+--------+--------+

Das obige INSERT s in bar , was zu:

führt
select * from bar;
+----+----------+--------+--------+
| id | user     | first  | last   |
+----+----------+--------+--------+
|  1 | RHill1   | Roger  | Hill   | 
|  2 | SRoad1   | Sally  | Road   | 
|  3 | FMount1  | Fred   | Mount  | 
|  4 | DMeadow1 | Darren | Meadow | 
|  5 | SRoad2   | Sharon | Road   | 
+----+----------+--------+--------+

Um die "1" am Ende von Benutzernamen zu entfernen,

INSERT INTO bar (id,user,first,last)
(SELECT f3.id,
        CONCAT(
            SUBSTRING(f3.first,1,1),
            f3.last,
            CASE f3.cnt WHEN 1 THEN '' ELSE f3.cnt END),
        f3.first,
        f3.last
 FROM (
    SELECT
        f.id,
        f.first,
        f.last,
        (
            SELECT COUNT(*) 
            FROM foo f2
            WHERE SUBSTRING(f2.first,1,1) = SUBSTRING(f.first,1,1)
            AND f2.last = f.last AND f2.id <= f.id
        ) as cnt
    FROM foo f) f3)