skip to Main Content

My site is a school web site.

The teacher choose every day a random student from the ‘students’ table, and update it in ‘randoms’ table.

Now I’m trying something else for making it easier.

I want the table ‘randoms’ will be updated every hour without the teacher, automatically.

it means that every hour, random student from the ‘students’ table will be updated in the ‘randoms’ table.

Is someone know how to do that?
thanks so much!!

2

Answers


  1. If you have access to the host you can use cron to program a query which makes the task (assuming you are on linux). The query should be something like:

    set @student = select name from student order by rand() limit 1;
    update table randoms set student=@student;
    

    And you can create the cron task issuing in the console crontab -e and adding a line like this:

    0 */1 * * * mysql -u<user> -p<password> -D <database> -e "<sql command in one line>"
    

    This will execute your query every hour. If you prefer executing it every 2 hours or more, just replace */1 for the desired period of time. If you are on Windows you can also run the sql using the Task Scheduler.

    Login or Signup to reply.
  2. This is how it is done in mysql.

     CREATE EVENT update_random
        ON SCHEDULE EVERY 1 HOUR
        COMMENT 'Updates Random Table with Student from Student Table every hour'
        DO 
        BEGIN
         UPDATE TABLE random SET student = (SELECT student FROM student ORDER BY RAND() LIMIT 1);
        END
    

    There is some further information to enable disable the event scheduler in the mysql docs if you are having any issues with that working https://dev.mysql.com/doc/refman/5.7/en/events-configuration.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search