假设我有一个像这样的MySQL结构......
+--------------+--------------------+-------------------+
| tdate | tuser | tvalue |
+--------------+--------------------+-------------------+
| 11:16:48 | John | 10 |
+--------------+--------------------+-------------------+
| 11:16:38 | John | 40 |
+--------------+--------------------+-------------------+
| 11:16:28 | Lisa | 50 |
+--------------+--------------------+-------------------+
| 10:16:48 | Lisa | 20 |
+--------------+--------------------+-------------------+
和这样的php查询:
<?php
$username = 'test';
$sql=mysqli_query($db,"SELECT * FROM t ORDER BY tid DESC LIMIT 20");
while($row=mysqli_fetch_array($sql))
{
$tuser= $row['tuser'];
$tvalue= $row['tvalue'];
$tdate= $row['tdate'];
?>
<div id="<?php echo $tvalue; ?>" class="message_box">
<?php echo $tdate; ?> -
<?php echo $tvalue; ?> -
<?php echo $tuser; ?>
</div>
<?php
}
?>
目前按行显示每行的mysql表:
2016-02-22 11:16:48 - 10 - John
2016-02-22 11:16:38 - 40 - John
2016-02-22 11:16:28 - 50 - Lisa
2016-02-22 10:16:48 - 20 - Lisa
我希望看到这样:
2016-02-22 11:16:48 - 50 - John
2016-02-22 11:16:28 - 50 - Lisa
2016-02-22 10:16:48 - 20 - Lisa
意味着循环必须在60秒内为同一用户创建新行的情况下总结值.Lisa有两行,但由于有一小时的时间戳差异,因此必须列出像往常一样......它需要自动更新,这意味着它最初会显示John的值为40,但是在添加新行10秒后,它必须相应地更新为50。还有MYSQL QUERY LIMIT为20的问题可能会破坏在60秒内插入的行并给出错误的总值计算。我知道它很难,但有人有一个简单的解决方案吗?
感谢Asur我目前有这个:
SELECT ROUND(UNIX_TIMESTAMP(tdate) DIV 60) AS time,tuser,SUM(tvalue)
FROM t
GROUP BY EXTRACT(DAY_HOUR FROM tdate),tuser
ORDER BY tid DESC
LIMIT 20;
但问题是如果最后一个数据库行是JOHN,如果在同一小时内已经有一个John行,那么他将不会列在最后。
IF I HAVE:
JOHN 10
GEORGE 10
GEORGE 10
JOHN 10
It will list:
JOHN 20
GEORGE 20
And it should be the other way arround, where the last row counts:
GEORGE 20
JOHN 20
答案 0 :(得分:1)
我建议你直接在sql查询中执行,如下所示:
SELECT ROUND(UNIX_TIMESTAMP(tdate) DIV 60) AS time,tuser,SUM(tvalue)
FROM t
GROUP BY time,tuser
ORDER BY tid DESC
LIMIT 20;
这在优化和花费时间方面要好得多。
答案 1 :(得分:0)
替换此查询:
SELECT * FROM t ORDER BY tid DESC LIMIT 20
用这个:
SELECT tdate , sum(tvalue), tuser FROM t
group by tuser, DATE_FORMAT(tdate , '%Y-%m-%d %h:%i')
ORDER BY tid DESC LIMIT 20