简体   繁体   中英

SQL query: Update single attribute (column) value to k different values

I want to replace an attribute value by k different values (which I am getting from a list, hence k can change depending on the size of the list). Also, the k different values need to be updated in equal proportion.

eg There is an attribute Education with value University .

Now, I want to update the table where University should be replaced with Bachelors , Masters or Doctorate .

If there are 100 tuples where Education = University then:
33 should be updated to Bachelors ,
33 to Masters and
34 to Doctorate .

Note: In the given example k = 3. I would require a query which is workable for different values of k . Since, I would be integrating this query in mysql with python, you may write any variable to represent k and list indices.

Edit: A naive approach is to first store the count of tuples where Education = University . Then dividing that count by k (where k is the length of list) and running the update query repeatedly in a for loop until the values from the list are exhausted.
In the update query, I limit the number of rows affected by setting limit = count / k . Is there a more efficient way to achieve the same?

There is a huge number of different solutions in different way for different environment. I show you an idea how to solve it with a single update. It isn't quite optimal one but it does its work alright. Let's say we have two tables – student(id, education) and education (name). Then, here you are:

update student
    set education_new = (
        select
            --s2.id, s2.education,
            e1.name
        from (
                select (select count(*) from education x where x.rowid <= e.rowid) id, name  from education e
            ) e1,
            (
                select
                    s.id, (select count(*) from student x where x.education = 'University' and x.rowid <= s.rowid) % (select count(*) from education) + 1 as e_id
                from student s
            ) s2
        where
            e1.id = s2.e_id
            and s2.id = student.id
        )
where education = 'University'

In this case, you also need to run extra update:

update student
    set education = education_new
where
    education <> education_new
    and education_new is not null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM