SQl Update from table of random Names

后端 未结 2 2097
栀梦
栀梦 2021-01-26 10:23

I Have a table of random names, simply 3 columns(id, firstname, lastname).

I am trying to have SQL update an entire table of names

相关标签:
2条回答
  • 2021-01-26 10:35

    Here is the query:

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

    It only updates a row in testnames when the random id chosen by the expression matches an id in the table. Are the id values in rndnames all populated?

    If your table is not very big and it has an id, here is another approach:

    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;
    

    EDIT:

    I think this will also work:

    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
                     );
    
    0 讨论(0)
  • 2021-01-26 10:41
    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
    
    0 讨论(0)
提交回复
热议问题