2013-07-04 205 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