MySQL: обновить несколько строк случайными значениями - PullRequest
0 голосов
/ 03 августа 2020

У меня есть таблица под названием rainfall. Он имеет 2 столбца ( sensorID , площадь , время , количество осадков , redalert )

enter image description here

I want to fill the time column with random times in intervals of 5 minutes (e.g 12:55, 04:30, 07:45) . I managed to get the random times by using this Python code:

import mysql.connector
import random
import datetime
import time


MINTIME = datetime.datetime(2020,4,1,0,0,0)
MAXTIME = datetime.datetime(2020,7,1,0,0,0)

mintime_str = int(time.mktime(MINTIME.timetuple())) #convert date to INT
maxtime_str = int(time.mktime(MAXTIME.timetuple())) #convert date to INT

no_steps = (maxtime_str - mintime_str)//(5*6) #state the number of minutes interval to 5 minutes

sql = "UPDATE rainfall SET date = %s"
rand = ''

for RECORD in range(108):
    random_slot = random.randint(0, no_steps)
    random_ts = mintime_str + 5*60 * random_slot
    RANDOMTIME = datetime.datetime.fromtimestamp(random_ts)
    rand = datetime.datetime.strftime(RANDOMTIME, '%H:%M')


val = (rand,)


mycursor.execute(sql, val)

raindb.commit()

print(mycursor.rowcount, "record(s) affected")

The problem is that this code fill all rows in time with 1 value only:

введите описание изображения здесь

Мне нужны разные значения в каждой строке. Это нормально, если в некоторых строках есть повторяющиеся значения времени.

Заранее спасибо

Ответы [ 2 ]

2 голосов
/ 03 августа 2020

Я бы использовал rand() следующим образом:

update rainfall 
set time = sec_to_time(floor(rand() * 60 * 60 * 24 / (5 * 60) * 5 * 60)

Выражение rand() * 60 * 60 * 24 дает вам случайное количество секунд, которое представляет время. Затем вы можете использовать floor() и умножение, чтобы округлить его до ближайших 5 минут. Наконец, time_to_sec() превращает его в time.

2 голосов
/ 03 августа 2020

Вы можете сделать это только с SQL:

update rainfall  
set time = concat(
  lpad(floor(rand() * 24), 2, '0'),
  ':',
  lpad(floor(rand() * 12) * 5, 2, '0')
); 
...