1

短的

  1. 我想要一个基于并插入SUM的列TABLE_ACRITERIA XTABLE_B.total_x
  2. 我想要一个基于并插入SUM的列TABLE_ACRITERIA YTABLE_B.total_y
  3. 问题:第 2 步未更新TABLE_B.total_y

表_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     |

TABLE_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:标准_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:标准_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预期更新。为什么?

4

1 回答 1

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

阅读关于 INSERT...ON DUPLICATE KEY UPDATE 的规范,我注意到了这一点:

如果 ... 匹配多行,则仅更新一行。通常,您应该尽量避免对具有多个唯一索引的表使用 ON DUPLICATE KEY UPDATE 子句。

所以复合键的语法有点麻烦,我个人会避免使用它。

于 2013-11-15T02:38:56.917 回答