每天计算/计算mysql结果

时间:2011-03-29 17:12:33

标签: php mysql sql database

假设我有一个名为“signups”的mysql表,其中包含以下值:

Name            Signup Date
dog            2008-05-14 18:53:30
cat            2008-05-14 12:13:20
mouse          2008-05-14 08:51:32
giraffe        2008-05-15 22:13:31
Moose          2008-05-16 13:20:30
monkey         2008-05-16 08:51:32
mongoose       2008-05-16 22:13:31
fish           2008-05-16 13:00:30

我想生成一份报告,说明每天有多少动物注册(我不关心一天中的时间)。因此,我从上面的示例表中寻找的最终结果是:

Date              Signups
2008-05-14         3
2008-05-15         1
2008-05-16         4

有没有办法在mysql中执行此操作,还是需要使用其他语言(如PHP)来计算总数?

感谢任何想法,谢谢

2 个答案:

答案 0 :(得分:9)

SELECT  DATE(Signup_Date) AS `Date`
        , COUNT(*) AS Signups 
FROM    `signups` 
GROUP BY 
        DATE(Signup_Date)

会准确地告诉你你的目的。

答案 1 :(得分:0)

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) unique not null,
created_date datetime not null
)
engine=innodb;

drop table if exists user_signup_summary;
create table user_signup_summary
(
signup_date date not null primary key,
counter int unsigned not null default 0
)
engine=innodb;

delimiter #

create trigger users_before_ins_trig before insert on users
for each row
begin
 insert into user_signup_summary (signup_date, counter) values (new.created_date, 1)
  on duplicate key update counter=counter+1;
end#

delimiter ;

insert into users (username, created_date) values
('f00', now()), ('bar', now()),
('alpha', now() - interval 1 day), ('beta', now() - interval 1 day),
('gamma', now() - interval 2 day);


select * from users;
select * from user_signup_summary;