1
- 我想
SUM
基於CRITERIA X
和插入TABLE_B.total_x
- 我想
SUM
列在TABLE_A
基於CRITERIA Y
並插入到TABLE_A
列TABLE_B.total_y
- 問題:步驟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
。 爲什麼?
我從來沒有以這種方式完成SUM。讓我看看它是否有效 – denormalizer
完美。這與我想要做的相似,但不知道該怎麼做。謝謝 – denormalizer
如果你可以解釋它,我仍然會對我爲什麼這樣做不起作用感興趣... – denormalizer