为你们一个难题的位。我可以提出钝的解决方法(下面),但我认为它会向大家展示是否有更优雅的解决方案。请记住,我正在寻找一个仅限PHP或MySql的解决方案。MySQL添加时间到列
表是'蜡烛2'。我有一个带有日期戳的MySQL TEXT列'time'(例如2010.08.13 19:30)。请不要问为什么它是一个文本字段:)。我有第二个TEXT列“时间范围”列出了时间的面额(例如'15m','30m','1h','4h'或'每日')。 'id'是主键。
我想将“时间范围”中的时间量添加到“时间”。例如,如果'time'=='2010.08.13 19:30'和'timeframe'== 15m,那么它会用'2010.08.13 19:45'更新'时间'(注意增加了15个分钟)。
这是我的想法是:
// PHP查询DB:
//using UNIX_TIMESTAMP to make the datetime usable by PHP
$sql = "SELECT UNIX_TIMESTAMP(time), timeframe, id FROM candles2";
$result = mysql_query($sql);
//loop through rows
while($row = mysql_fetch_array($result))
{
//call function to determine the appropriate # of seconds to add
$newTime = newTime($row['time'],$row['timeframe']);
//build UPDATE query and update row
$update_query = "UPDATE candles2 SET 'time'= FROM_UNIXTIME(" . $newTime . ") WHERE id='".$row['id']."'";
$update_result = mysql_query($update_query);
}
// PHP函数添加适当秒
function newTime($oldtime,$timeframe)
{
switch ($timeframe)
{
case "15m": return($oldtime + 15 * 60);
case "30m": return($oldtime + 30 * 60);
case "1h": return($oldtime + 60 * 60);
case "4h": return($oldtime + 240 * 60);
case "daily": return($oldtime + 1440 * 60);
default: die("whoops, something broke");
}
}