如何在Mysql中生成随机日期

时间:2013-06-28 12:04:37

标签: php mysql

       This is my table
       +----+---------------+
       | id | payperiod     |
       +----+---------------+
       |  1 | Weekly        |
       +----+---------------+
       |  2 | Monthly       |
       +----+---------------+

我需要使用查询来显示未来的两个日期NextPaydate和SecondNextPaydate与payperiod 如果payperiod是Weekly那么nextpaydate将是07/01/2013而secondnextpaydate将是07/07/2013

我用php代码做了解决方案,如下所示

$payperid = 'Weekly'; // value can be changed
if ($payperid == "Weekly") {
    $rand = rand(2,6);
    $diff = 7;
}
else if ($payperid=="Monthly") {
    $rand = rand(2,28);
    $diff = rand(30,31);    
}
$opt_in = date('Y-m-d');
$ed = strtotime($opt_in);

$paydate1_day   = date("d",mktime(date("H",$ed),date("i",$ed),date("s",$ed),date('m',$ed),date('d',$ed)+$rand,date('Y',$ed)));
$paydate1_month = date("m",mktime(date("H",$ed),date("i",$ed),date("s",$ed),date('m',$ed),date('d',$ed)+$rand,date('Y',$ed)));
$paydate1_year  = date("Y",mktime(date("H",$ed),date("i",$ed),date("s",$ed),date('m',$ed),date('d',$ed)+$rand,date('Y',$ed))); 
$paydate2_day   = date("d",mktime(date("H",$ed),date("i",$ed),date("s",$ed),date('m',$ed),date('d',$ed)+($diff),date('Y',$ed)));
$paydate2_month = date("d",mktime(date("H",$ed),date("i",$ed),date("s",$ed),date('m',$ed),date('d',$ed)+($diff),date('Y',$ed)));
$paydate2_year  = date("d",mktime(date("H",$ed),date("i",$ed),date("s",$ed),date('m',$ed),date('d',$ed)+($diff),date('Y',$ed)));

$nextpaydate = $paydate1_month / $paydate1_day / $paydate1_year 

$secondnextpaydate = $paydate2_month / $paydate2_day / $paydate2_year

请帮助如何处理mysql查询(如果condtion和rand函数)

1 个答案:

答案 0 :(得分:3)

我正在回答你标题中的问题,因为在查看你的描述后我不确定。

  

如何在Mysql中生成随机日期

UPDATE tablename SET datefield= ’1980-01-01′ + interval rand()*80000 day
来自Google搜索的

Takenrandom date mysql


可能的解决方案

根据我对你的描述的理解:

如何获得下周:

UPDATE tablename SET datefield = datefield + interval 1 weeks

如何获得下个月:

UPDATE tablename SET datefield = datefield + interval 1 months