0

我想按当前日期计算来自不同表的记录,并在新表中作为具有不同列的一行返回。该代码将每三个小时更新一次记录,并在当前日期更改时插入新记录。我在“created_at”列中有当前日期和时间数据(2013-05-20 14:12:12)。这是我当前的代码:

require_once('./db_connect.php');
$dbcon = new db;

//test to see if a specific field value is already in the DB 
public function in_table($table,$where) {
  $query = 'SELECT * FROM ' . $table . ' WHERE ' . $where;
  $result = mysqli_query($this->dbh,$query);
  $this->error_test('in_table',$query); 
  return mysqli_num_rows($result) > 0;
}

//running in background
while (true) {
   $select= "SELECT (SELECT CURDATE()) AS time," .
           "(SELECT COUNT(tweet_id) FROM tweets WHERE created_at= 'CURDATE() %') AS total_count," .
           "(SELECT COUNT(fid) FROM fun WHERE ftime= 'CURDATE() %') AS f_count," .
           "(SELECT COUNT(sid) FROM sad WHERE stime= 'CURDATE() %') AS s_count";

    $results = mysqli_query( $dbcon, $select );

    while($row = mysqli_fetch_assoc($result)) {
       $time = $row['time'];
       $total = $row['total_count'];
       $fcount = $row['f_count'];
       $scount = $row['s_count'];

       $field_values = 'time = "' . $time . '", ' . 'total_count = ' . $total . ', ' . 'fun_count = ' . $fcount . ', ' . 'sad_count = ' . $scount;

       if ($dbcon->in_table('count','time= "' . $time . '"')) {
         $update = "UPDATE count SET $field_values WHEN time= '$time'";
         mysqli_query( $dbcon, $update );
       }
       else {
         $insert = "INSERT INTO count SET $field_values";
         mysqli_query( $dbcon, $insert );
       }
   }

   //update record every 3 hour
   sleep(10800);
}

使用此代码,我无法获得计数记录。结果返回| 2013-05-18 | 0 | 0 | 0 |。我该如何纠正?

4

3 回答 3

2

我不熟悉 PHP,但是您可以使用以下命令检索今天任何时间日期的所有记录的计数:

     SELECT COUNT(tweet_id) 
     FROM   tweets 
     WHERE  created_at >= curDate()
     AND    created_at < date_add(curDate(), interval 1 day)

相当于说

     ..
     WHERE  created_at >= (today at midnight *incusive*)
     AND    created_at < (tomorrow at midnight *exclusive*)

更新:

这种方法的优点是索引友好。在使用WHERE DATE(Column) = currDate()工作时,它可以阻止数据库使用该列上的索引,从而使查询变慢。

于 2013-05-20T16:31:48.797 回答
1

更换你有这个的零件:

WHERE created_at= 'CURDATE() %'

有了这个:

WHERE DATE(created_at) = CURDATE()

您现有的WHERE子句created_at与字符串 constant进行比较CURDATE() %,它们永远不会匹配。

于 2013-05-20T15:35:04.340 回答
0

您正在与 比较created_at= 'CURDATE() %',它正在寻找确切的字符串,而不是函数的结果。如果该字段created_at是日期,它将永远不会匹配。

而且,您正在为所有方面这样做。

于 2013-05-20T15:33:04.790 回答