使用随机字符串更新新SQL列

时间:2014-09-10 23:49:25

标签: mysql sql

我有一张桌子,想要添加另一个字段identity

id | name | identity
 1 |  sam | 
 2 |  joe | 
 3 |  jen |

目前没有身份数据。我会在每一行填充5个随机字符串(例如:kdU3k)。

以这种方式更改/更新表的最佳方法是什么?


由于我有一个PHP后端,我可以在技术上循环一个其中identity = null的SQL语句,但我想知道如何只使用SQL。

1 个答案:

答案 0 :(得分:4)

虽然我建议这样做,主要是因为MySQL使某些方面不那么有趣,这可以完全在MySQL DML中完成,甚至不使用用户定义的程序。程序允许使用程序while循环等。

我创建了sqlfiddle。第一步是创建随机值;在这种情况下,他们也确保在表格中有所区别,这样可以确保减少一件事情。

-- Create lots of random values without using a proceure and loop.
-- There may be duplicates created. Could be a temporary table.
-- Would be much simplified if there was already a numbers table.
create table idents (value char(5));
insert into idents (value) values (left(md5(rand()), 5));               -- 1
insert into idents (value) select (left(md5(rand()), 5)) from idents;   -- 2
insert into idents (value) select (left(md5(rand()), 5)) from idents;   -- 4
insert into idents (value) select (left(md5(rand()), 5)) from idents;
insert into idents (value) select (left(md5(rand()), 5)) from idents;
insert into idents (value) select (left(md5(rand()), 5)) from idents;
insert into idents (value) select (left(md5(rand()), 5)) from idents;   -- 64

-- Delete duplicate values. While there may be a rare duplicate we will
-- still be left with a good many random values. A similar process
-- could also be used to weed out existing used values.
delete from idents
where value in (
  -- The select * is for another MySQL quirk
  select value from (select * from idents) i
  group by value
  having count(value) > 1);

然后随机值必须与每个人相关联。这是通过对" ROW_NUMBER"的可怕模拟来完成的。关于派生关系和联接。

set @a = 0;
set @b = 0;

-- Now here is UGLY MYSQL MAGIC, where variables are used to simulate
-- ROW_NUMBER. YMMV, it "Works Here, Now". Note the very suspicious
-- hack to assign @b back to 0 "for each" joined item.
update people p2
  join (select p.id, i.value
    -- Give each person record a row number
    from (select @a := @a + 1 as rn1, id, @b := 0 as hack from people) p
    -- Give each random number a row number
    join (select @b := @b + 1 as rn2, value from idents) i
    -- And join on row number
    on p.rn1 = i.rn2) pv
  on p2.id = pv.id
set p2.identity = pv.value

再次,YMMV。