实时计算多个表中的记录

时间:2013-05-20 15:27:44

标签: php mysql

我想从不同的表中按当前日期计算记录,并在新表中以不同的列返回一行。代码将每三个小时更新一次记录,并在当前日期更改时插入新记录。我在" 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 |。我怎么能纠正这个?

3 个答案:

答案 0 :(得分: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()时,它可以防止数据库使用该列上的索引,从而减慢查询速度。

答案 1 :(得分:1)

更换您拥有此部件的部件:

WHERE created_at= 'CURDATE() %'

用这个:

WHERE DATE(created_at) = CURDATE()

您现有的WHERE子句正在将created_at与字符串常量CURDATE() %进行比较,并且永远匹配。

答案 2 :(得分:0)

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

而且,无论如何,你都是这样做的。