1

我有 2 个表,table_a 和 table_b,创建和填充如下:

DROP TABLE IF EXISTS `table_a`;
CREATE TABLE `table_a` (
  `a_id` bigint(20) NOT NULL auto_increment,
  `user_name` varchar(255) default NULL,
  `created_at` datetime default NULL,
  `running_count` int default NULL,
  PRIMARY KEY  (`a_id`)
);

DROP TABLE IF EXISTS `table_b`;
CREATE TABLE `table_b` (
  `b_id` bigint(20) NOT NULL auto_increment,
  `user_name` varchar(255) default NULL,
  `start` datetime default NULL,
  `end` datetime default NULL,
  `total_count` int default NULL,
  PRIMARY KEY  (`b_id`)
);

insert into table_a values (NULL, '1', '2013-07-05 01:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 02:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 02:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 03:00:00', 2);
insert into table_a values (NULL, '1', '2013-07-05 07:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 08:00:00', 1);

insert into table_b values (NULL, '1', '2013-07-05 00:00:00', '2013-07-05 06:00:00', 0);
insert into table_b values (NULL, '1', '2013-07-05 06:00:01', '2013-07-05 12:00:00', 0);

下面的查询使用总数更新 table_b:

update table_b b
set 
total_count= 
(
          SELECT  IFNULL(SUM(a.running_count),0) total_count
          FROM    table_a a
          where a.created_at BETWEEN b.start and b.end
          and a.user_name=b.user_name
          and a.created_at between '2013-07-05 00:00:00' and '2013-07-05 23:59:59'
);

结果很好:

+------+-----------+---------------------+---------------------+-------------+
| b_id | user_name | start               | end                 | total_count |
+------+-----------+---------------------+---------------------+-------------+
|    1 | 1         | 2013-07-05 00:00:00 | 2013-07-05 06:00:00 |           5 |
|    2 | 1         | 2013-07-05 06:00:01 | 2013-07-05 12:00:00 |           2 |
+------+-----------+---------------------+---------------------+-------------+

但是我需要第一个计数是 4 而不是 5,因为在 2013-07-05 02:00:00 有一条重复记录,应该算作 1 而不是 2。

如果有多个重复的时间戳,如何将更新查询修改为仅计数 1?

4

1 回答 1

1

代替:

FROM    table_a a

和:

FROM   (
       SELECT  DISTINCT created_at
       ,       user_name
       ,       running_count
       FROM    table_a
       ) a
于 2013-07-04T21:38:38.217 回答