2013-11-15 70 views
1

INSERT SELECT上的重複不更新

  1. 我想SUM基於CRITERIA X和插入TABLE_B.total_x
  2. 我想SUM列在TABLE_A基於CRITERIA Y並插入到TABLE_ATABLE_B.total_y
  3. 問題:步驟2不更新TABLE_B.total_y

LONG

TABLE_A:數據

| year | month | type | total | 
--------------------------------------- 
| 2013 | 11 | down | 100 | 
| 2013 | 11 | down | 50 | 
| 2013 | 11 | up | 60 | 
| 2013 | 10 | down | 200 | 
| 2013 | 10 | up | 15 | 
| 2013 | 10 | up | 9  | 

表-B:結構

CREATE TABLE `TABLE_B` (
    `year` INT(4) NULL DEFAULT NULL, 
    `month` INT(2) UNSIGNED ZEROFILL NULL DEFAULT NULL, 
    `total_x` INT(10) NULL DEFAULT NULL, 
    `total_y` INT(10) NULL DEFAULT NULL, 
    UNIQUE INDEX `unique` (`year`, `month`) 
) 

SQL:CRITERIA_X

INSERT INTO TABLE_B (
`year`, `month`, `total_x` 
) 
SELECT 
    t.`year`, t.`month`, 
    SUM(t.`total`) as total_x 
FROM TABLE_A t 
WHERE 
    t.`type` = 'down' 
GROUP BY 
    t.`year`, t.`month` 
ON DUPLICATE KEY UPDATE 
    `total_x` = total_x 
; 

SQL:CRITERIA_Y

INSERT INTO TABLE_B (
`year`, `month`, `total_y` 
) 
SELECT 
    t.`year`, t.`month`, 
    SUM(t.`total`) as total_y 
FROM TABLE_A t 
WHERE 
    t.`type` = 'up' 
GROUP BY 
    t.`year`, t.`month` 
ON DUPLICATE KEY UPDATE 
    `total_y` = total_y 
; 

第二SQL(CRITERIA_Y)如預期不更新total_y爲什麼?

回答

2

我會做另一種方式

insert into TABLE_B (year, month, total_x, total_y) 
select year, month 
    , sum (case [type] when 'down' then [total] else 0 end) [total_x] 
    , sum (case [type] when 'up' then [total] else 0 end) [total_y] 
from TABLE_A 
group by [year], [month] 

或者使用兩個子查詢的方式是

insert into TABLE_B (year, month, total_x, total_y) 
select coalesce(t1.year, t2.year) year 
    , coalesce(t1.month, t2.month) month 
    , t1.total_x total_x 
    , t2.total_y total_y 
from (select year, month, sum(total) total_x 
     from TABLE_A where [type]='down') t1 
full outer join 
    (select year, month, sum(total) total_y 
     from TABLE_A where [type]='up') t2 
    on t1.year = t2.year and t1.month = t2.month 

或者使用工會在INSERT

insert into TABLE_B (year, month, total_x, total_y) 
select year, month, sum(total_x), sum(total_y) 
from ( 
    select year, month, sum(total) total_x, 0 total_y 
    from TABLE_A where [type]='down' 
    group by year, month 
    union 
    select year, month, 0 total_x, sum(total) total_y 
    from TABLE_A where [type]='up' 
    group by year, month) t 
group by year, month 

閱讀規格... ON DUPLICATE KEY UPDATE,我注意到這個:

如果...匹配多行,則只更新一行。通常,您應該儘量避免在具有多個唯一索引的表上使用ON DUPLICATE KEY UPDATE子句。

因此,使用複合鍵的語法很麻煩,我個人會避免使用它。

+0

我從來沒有以這種方式完成SUM。讓我看看它是否有效 – denormalizer

+0

完美。這與我想要做的相似,但不知道該怎麼做。謝謝 – denormalizer

+0

如果你可以解釋它,我仍然會對我爲什麼這樣做不起作用感興趣... – denormalizer