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
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
);
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