SQl从随机名称表更新

时间:2014-02-04 18:25:34

标签: mysql sql

我有一个随机名称表,只有3列(idfirstnamelastname)。

我正在尝试让SQL更新一个包含此表中随机选择名称的整个名称表。

这是我正在使用的SQL。它似乎适用于某些记录,但它并不总是完成所有记录,有时会离开NULLS,或者不总是更新所有行。有时它会影响9行,有时会影响11行......想法?

update TestNames,rndnames
set TestNames.fname = rndnames.FirstName,TestNames.lname=rndnames.LastName
where rndnames.ID=floor(1+(rand()*600))

答案:

update
TestNames left join 
(select ID,
floor(1+(rand()*600)) as rndid
from TestNames) as TN on TN.ID=TestNames.id
left join rndnames on TN.rndid=rndnames.id
set TestNames.fname=rndnames.FirstName,TestNames.lname=rndnames.LastName

2 个答案:

答案 0 :(得分:1)

以下是查询:

update TestNames t cross join
       rndnames r
    set t.fname = r.FirstName,
        t.lname = r.LastName
    where r.ID = floor(1+(rand()*600));

当表达式选择的随机ID与表中的id匹配时,它仅更新testnames中的行。 id中的rndnames值是否全部填充?

如果你的桌子不是很大而且它有一个id,这是另一种方法:

update TestName t join
       (select t.*,
               (select id from rndnames order by rand() limit 1) as rndid
        from testname t
       ) tr
       on t.id = tr.id join
       rndnames r
       on t.rndid = r.id
    set t.fname = r.FirstName,
        t.lname = r.LastName;

编辑:

我认为这也有效:

update TestNames t cross join
       rndnames r
    set t.fname = r.FirstName,
        t.lname = r.LastName
    where r.ID = (select id
                  from rndnames
                  order by rand()
                  limit 1
                 );

答案 1 :(得分:0)

update
TestNames left join 
(select ID,
floor(1+(rand()*600)) as rndid
from TestNames) as TN on TN.ID=TestNames.id
left join rndnames on TN.rndid=rndnames.id
set TestNames.fname=rndnames.FirstName,TestNames.lname=rndnames.LastName