2013-07-04 122 views
1

我有2个表,表-A和表-B,创建和填充如下:SQL更新忽略重复

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); 

下面的更新查询表-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,因为有一个重复的re在2013-07-05 02:00:00,应该算作1而不是2。

如何修改更新查询以只计数1如果有多个重复时间戳?

回答

1

替换:

FROM table_a a 

有:

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

真棒,该诀窍。为了加快速度,我在where子句中添加了一个时间范围,因为table_a可能很大。 – keithc