目前我正在使用 php/mysql 和项目的一部分,我向用户展示了他在网站上发布的帖子总数、今天的帖子数以及关注他的 ppl 数
对于目前我正在做的
SELECT
(SELECT COUNT(*) FROM posts WHERE userId='{$u->id}) as totalposts,
(SELECT COUNT(*) FROM posts WHERE userId='{$u->id} and DATE(datePosted) = DATE(NOW())) as todayposts,
(SELECT COUNT(*) FROM user_follower WHERE followedId='{$u->id}') as myfollowers");
这个查询给了我 3 个数字,即总帖子数、今天帖子数和关注用户总数
关键是我想在这个数字旁边显示一个条形图,代表过去一周的用户活动(曲线或条形图可以告诉用户他是否正在下降或增加等。)
这个查询现在返回的例子
totalposts|todayposts|myfollowers|
100 | 4 | 300 |
但因为我现在还需要条形图来显示他的帖子数天。我做了
SELECT
(SELECT COUNT(*) FROM posts WHERE userId=2) as tpT,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 1 DAY ) as tp1,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 2 DAY ) as tp2,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 3 DAY ) as tp3,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 4 DAY ) as tp4,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 5 DAY ) as tp5,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 6 DAY ) as tp6,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) <= DATE(NOW()) - INTERVAL 7 DAY ) as tp7,
(SELECT COUNT(*) FROM posts WHERE userId=2 and DATE(timePosted) = DATE(NOW())) as tdvT
Result
tpT|tp1|tp2|tp3|tp4|tp5|tp6|
100|96 | 90| 90| 89|80 |64 |
其中 tps(1) 代表 WHERE 帖子在当前日期之前发布 - 1 天。
那么我怎么能在语句中做这样的循环呢?还是我应该保持这种状态?
目前它并没有造成太大的麻烦。0.0008 秒的执行时间,非常棒。
还有更好的方法吗?
我看起来很愚蠢:p
提前致谢
编辑
对于未来的谷歌人。
我最终做了
$v=$this->db->query("SELECT count(*) as count,date(timePosted) as day FROM `posts` where userId = {$u->id} group by date(timePosted)");
$pts=[];
for($i=0; $i <= 6; $i++){
$pts[date('Y-m-d',strtotime(date('Y-m-d')."- $i Day"))]='0';
$vs[date('Y-m-d',strtotime(date('Y-m-d')."- $i Day"))]='0';
}
foreach($v->result() as $s){
if(isset($vs[$s->day]))$vs[$s->day]=$s->count;
}
因此,为了执行时间,我最终让 php 处理它。