我认为您不能在ON DUPLICATE
. MySQL 看到你的 SQL 是这样的:
insert into report_count_assets
expr
on duplicate key update
...
ON DUPLICATE 不知道发生了什么expr
,它只知道它有一个重复的行要处理。在不知道内部发生了什么的expr
情况下,没有count
s 可以操作的上下文。此外,您应该values
在 UPDATE 中使用:
您可以使用子句中的VALUES(col_name)
函数UPDATE
来引用语句INSERT
部分中的列值INSERT ... ON DUPLICATE KEY UPDATE
。
并且values(count(x))
不是有效的语法。但是values(column_name)
是有效的,所以这应该有效:
INSERT INTO report_count_assets
(product_id, asset_count, asset_type_image, asset_type_video, asset_type_sound, asset_type_install)
SELECT products.product_id,
count(product_assets.asset_id),
count(case when assets.asset_type_id=1 THEN 1 END),
count(case when assets.asset_type_id=2 THEN 1 END),
count(case when assets.asset_type_id=3 THEN 1 END),
count(case when assets.asset_type_id=11 THEN 1 END)
FROM products
LEFT JOIN product_assets USING (product_id)
LEFT JOIN assets USING (asset_id)
WHERE products.brand_id=671
ON DUPLICATE KEY UPDATE
asset_count = values(asset_count),
asset_type_image = values(asset_type_image),
asset_type_video = values(asset_type_video),
asset_type_sound = values(asset_type_sound),
asset_type_install = values(asset_type_install);
我不得不product_id
猜测report_count_assets
.
如果这不起作用(显然它不起作用),那么您可以通过预先计算 SELECT 来艰难地做到这一点。创建一个临时表:
create temporary table t (
product_id int,
product_count int,
assets1 int,
assets2 int,
assets3 int,
assets11 int
)
填充它:
INSERT INTO t (product_id, product_count, assets1, assets2, assets3, assets11)
SELECT products.product_id,
count(product_assets.asset_id),
count(case when assets.asset_type_id=1 THEN 1 END),
count(case when assets.asset_type_id=2 THEN 1 END),
count(case when assets.asset_type_id=3 THEN 1 END),
count(case when assets.asset_type_id=11 THEN 1 END)
FROM products
LEFT JOIN product_assets USING (product_id)
LEFT JOIN assets USING (asset_id)
WHERE products.brand_id=671
然后使用该临时表执行您真正想做的插入:
insert into report_count_assets
select product_id, product_count, assets1, assets2, assets3, assets11
from t
on duplicate key update
asset_count = values(product_count),
asset_type_image = values(assets1),
asset_type_video = values(assets2),
asset_type_sound = values(assets3),
asset_type_install = values(assets11)