У меня есть таблица, содержащая эти данные:
"germination_day","2019-01-02","2019-03-02","08:00:00","18:00:00","100","0","2","0","0","0","0","0","24","54","0","1300","24","120"
"germination_night","2019-01-02","2019-03-02","18:00:00","08:00:00","0","96","0","0","0","0","0","0","25","40","0","1300","24","120"
" flowering_day","2019-03-02","2019-06-02","08:00:00","06:00:00","0","0","0","0","100","0","0","10","25","40","0","1300","24","120"
"flowering_night","2019-03-02","2019-06-02","06:00:00","08:00:00","0","0","0","0","0","0","0","0","0","0","0","0","24","120"
"vegetation_day ","2019-06-02","2019-09-02","08:00:00","06:00:00","0","0","0","0","100","0","0","10","25","40","0","1300","24","120"
"vegetation_night","2019-06-02","2019-09-02","06:00:00","08:00:00","0","0","0","0","0","0","0","0","0","0","0","1300","24","120"
"maturation_day","2019-09-02","2019-12-31","08:00:00","09:00:00","0","0","0","0","0","0","0","0","0","0","0","1300","24","120"
"maturation_night","2019-09-02","2019-12-31","09:00:00","08:00:00","0","0","0","0","0","0","0","0","0","0","0","1300","24","120"
Это визуальная схема таблицы: ![enter image description here](https://i.stack.imgur.com/clLZY.png)
Эта таблица содержит параметры дляобстановка зеленого дома.Передавая текущий день и время, мне нужно получить строку данных с прошедшим днем в диапазоне между start_date и end_data и прошедшим текущим временем в диапазоне между start_hour и end_hour.
Каждая фаза состоит издень и ночь.он начинается в 8 утра и заканчивается в 8 утра следующего дня.
Это код, который я написал до сих пор.Это не завершено, потому что мои навыки в SQL не так велики.Вот почему мне нужна помощь:
SET @CurrentDate = CURDATE();
SET @CurrentTime = NOW();
SELECT start_hour, end_hour,
CASE
WHEN CAST( CONCAT(@CurrentDate, ' ', end_hour) as DATETIME ) > CAST( CONCAT(@CurrentDate, ' ', '00:00:00') as DATETIME ) AND CAST( CONCAT(@CurrentDate, ' ', end_hour) as DATETIME ) <= CAST( CONCAT(@CurrentDate, ' ', '08:00:00') as DATETIME )
THEN CAST( CONCAT(@CurrentDate, ' ', end_hour) as DATETIME ) = CAST( CONCAT(@CurrentDate, ' ', end_hour) as DATETIME ) + INTERVAL 1 DAY
WHEN CAST( CONCAT(@CurrentDate, ' ', start_hour) as DATETIME ) = CAST( CONCAT(@CurrentDate, ' ', end_hour) as DATETIME )
THEN CAST( CONCAT(@CurrentDate, ' ', start_hour) as DATETIME ) - INTERVAL 1 MINUTE
WHEN NOW() >= CAST( CONCAT(@CurrentDate, ' ', start_hour) as DATETIME )
THEN "Day phase"
WHEN NOW() < CAST( CONCAT(@CurrentDate, ' ', start_hour) as DATETIME ) OR ( NOW() >= CAST( CONCAT(@CurrentDate, ' ', start_hour) as DATETIME ) AND NOW() < CAST( CONCAT(@CurrentDate, ' ', end_hour) as DATETIME ) - INTERVAL 1 DAY)
THEN "It goes to the night phase"
END AS expense_amt
FROM `RECIPE_TABLE`
WHERE CURDATE() >= start_date
AND CURDATE() < end_date
Раньше я использовал файл .CSV с Python.Однако теперь для лучшей производительности мне нужно реализовать запрос в MySQL.
Это был рабочий код (возможно, его можно улучшить):
def getCurRow(self):
currentTime = datetime.datetime.now().replace(microsecond=0)
inFile = open(self._recipe_file, 'rb')
reader = csv.reader(inFile, skipinitialspace=False)
headers = reader.next();
try:
for index, row in enumerate(reader):
row = [element.strip() for element in row]
if(len(row)>=0):
print("Row: "+str(row))
sDate = datetime.datetime.strptime(row[1].strip(), "%d/%m/%Y")
eDate = datetime.datetime.strptime(row[2].strip(), "%d/%m/%Y")
self.sTime = datetime.datetime.strptime(currentTime.strftime('%d/%m/%Y')+" "+row[3].strip(), "%d/%m/%Y %H:%M")
self.eTime = datetime.datetime.strptime(currentTime.strftime('%d/%m/%Y')+" "+row[4].strip(), "%d/%m/%Y %H:%M")
#sTime and eTime will be also considered for the preparation of the solution
self.sTime.replace(second=0)
self.eTime.replace(second=0)
if (eDate <= sDate):
print("Impossible eDate <= sDate ")
break
print("eTime : "+str(self.eTime)+" cond1 : "+str(currentTime.replace(hour=0,minute=0,second=0))+" "+"cond2 : "+str(currentTime.replace(hour=8,minute=0,second=0)))
if (self.eTime > currentTime.replace(hour=0,minute=0,second=0) and self.eTime <= currentTime.replace(hour=8,minute = 0,second=0)):
self.eTime = self.eTime + datetime.timedelta(days=1)
if (currentTime <= eDate and currentTime >= sDate): # check data
if (self.sTime == self.eTime):
print("sTime = eTime")
self.sTime = self.sTime - datetime.timedelta(minutes=1)
print ("currentTime: "+str(currentTime))
print ("startingDate: "+str(sDate))
print ("endDate: "+str(eDate))
print ("startingTime: "+str(self.sTime))
print ("endTime: "+str(self.eTime))
if(currentTime >=self.sTime) and (currentTime < self.eTime):
print("Day phase")
self.phaseID = index
self.phase = str(row[0].strip())
return row
break
elif (currentTime < self.sTime) or (currentTime >= self.eTime) and (currentTime < eDate - datetime.timedelta(days=1)):
#it consider the following line, the night phase
print("It goes to the night phase")
row = reader.next()
print("Night phase: "+str(row))
self.phaseID = index+1
print("phaseID: "+str(self.phaseID))
self.phase = str(row[0].strip())
self.sTime = datetime.datetime.strptime(currentTime.strftime('%d/%m/%Y')+" "+row[3].strip(), "%d/%m/%Y %H:%M")
self.eTime = datetime.datetime.strptime(currentTime.strftime('%d/%m/%Y')+" "+row[4].strip(), "%d/%m/%Y %H:%M")
self.eTime = self.eTime + datetime.timedelta(days=1)
return row
break
else:
print("Next range time")
continue
else:
print("Next range days")
continue
else:
print("There are no rows")
else:
sys.exit('Error: File configuration ended')
return None
except csv.Error as e:
sys.exit('File %s, line %d: %s' % (in_file, reader.line_num, e))
except ValueError as e:
sys.exit('Error: Configuration file not well formatted.\n%s' % e)
finally:
inFile.close()