mysql - SQL query: Update single attribute (column) value to k different values -
i want replace attribute value k different values (which getting list, hence k can change depending on size of list). also, k different values need updated in equal proportion.
e.g. there attribute education
value university
.
now, want update table university
should replaced bachelors
, masters
or doctorate
.
if there 100 tuples education = university
then:
33 should updated bachelors
,
33 masters
,
34 doctorate
.
note: in given example k = 3. require query workable different values of k. since, integrating query in mysql python, may write variable represent k , list indices.
edit: naive approach first store count
of tuples education = university
. dividing count k (where k length of list) , running update query repeatedly in loop until values list exhausted.
in update query, limit number of rows affected setting limit
= count / k. there more efficient way achieve same?
there huge number of different solutions in different way different environment. show idea how solve single update. isn’t quite optimal 1 work alright. let’s have 2 tables – student(id, education) , education (name). then, here are:
update student set education_new = ( select --s2.id, s2.education, e1.name ( select (select count(*) education x x.rowid <= e.rowid) id, name education e ) e1, ( select s.id, (select count(*) student x x.education = 'university' , x.rowid <= s.rowid) % (select count(*) education) + 1 e_id student s ) s2 e1.id = s2.e_id , s2.id = student.id ) education = 'university'
in case, need run update:
update student set education = education_new education <> education_new , education_new not null
Comments
Post a Comment