SQL更新忽略重复项

时间:2013-07-04 21:35:33

标签: mysql sql database duplicates

我有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?

1 个答案:

答案 0 :(得分:1)

替换:

FROM    table_a a

使用:

FROM   (
       SELECT  DISTINCT created_at
       ,       user_name
       ,       running_count
       FROM    table_a
       ) a