Mysql

MySQL:插入到選擇問題

  • August 24, 2019

考慮下表:

=> table1
| aid |
| --- |
| a1  |
| a1  |
| a3  |
| a2  |
| ... |

=> table2
| aid | count | va    | vb    |
| --- | ----- | ----- | ----- |
| a1  | c1    | va1   | vb1   | 
| a2  | c2    | va2   | vb2   |
| ... | ...   | ...   | ...   |

基本上,table2聚合來自其他幾個表的數據,包括來自table1. table2在 MySQL 中更新數據的一種方法是:

INSERT INTO `table2`(`aid`, `count`)
SELECT `src`.`aid`, `src`.`count` FROM
(
   SELECT `aid`, COUNT(`aid`) AS `count`
   FROM `table1`
   GROUP BY `aid`
) AS `src`
ON DUPLICATE KEY UPDATE `table2`.`count` = `src`.`count`

雖然這段程式碼有效,但它似乎很羅嗦(繞圈子)。

首先,更好的方法是:

INSERT INTO `table2`(`aid`, `count`)
SELECT `aid`, COUNT(`aid`) AS `count`
FROM `table1`
GROUP BY `aid` AS `src`
ON DUPLICATE KEY UPDATE `table2`.`count` = `src`.`count`

不幸的是,由於一些未知的原因,這種更直接的方法不起作用。

為什麼?

根據文件

換句話說,UPDATE子句中的VALUES( col_name )是指將插入的col_name的值,沒有發生重複鍵衝突。

因此,更直接的方法是:

INSERT INTO `table2`(`aid`, `count`)
SELECT `aid`, COUNT(`aid`) AS `count`
FROM `table1`
GROUP BY `aid`
ON DUPLICATE KEY UPDATE `table2`.`count` = VALUES(`count`)

引用自:https://dba.stackexchange.com/questions/246157