我想知道下面的INSERT ... ON DUPLICATE KEY语句有什么问题。它一直抱怨 错误代码:1054。未知列' A.NoTrans'在'字段列表'
INSERT INTO tableA (id, totalTrans)
SELECT A.id, A.NoTrans
FROM (
SELECT id, NoTrans, LastUpdatedOn
FROM tableB
UNION
SELECT id, TotalTrans, LastUpdatedOn
FROM tableC
) A
WHERE A.LastUpdatedOn >= '2015-06-26' AND A.LastUpdatedOn <= '2015-06-27'
GROUP BY A.id, A.NoTrans
ON DUPLICATE KEY UPDATE totalTrans = A.NoTrans
如果声明没有 ON DUPLICATE KEY UPDATE totalTrans = A.NoTrans
,则没有问题INSERT INTO tableA (id, totalTrans)
SELECT A.id, A.NoTrans
FROM (
SELECT id, NoTrans, LastUpdatedOn
FROM tableB
UNION
SELECT id, TotalTrans, LastUpdatedOn
FROM tableC
) A
WHERE A.LastUpdatedOn >= '2015-06-26' AND A.LastUpdatedOn <= '2015-06-27'
GROUP BY A.id, A.NoTrans
我尝试为UNION列添加别名,但问题仍然存在,例如
SELECT A.id, A.NoTrans AS 'NoOfTrans'
......
ON DUPLICATE KEY UPDATE totalTrans = NoOfTrans
答案 0 :(得分:0)
A
无法识别表格别名on duplicate key update
。它是select
语句的一部分,但不是insert
语句的一部分。而是使用VALUES()
函数:
INSERT INTO tableA (id, totalTrans)
SELECT A.id, A.NoTrans
FROM (
SELECT id, NoTrans, LastUpdatedOn
FROM tableB
UNION
SELECT id, TotalTrans, LastUpdatedOn
FROM tableC
) A
WHERE A.LastUpdatedOn >= '2015-06-26' AND A.LastUpdatedOn <= '2015-06-27'
GROUP BY A.id, A.NoTrans
ON DUPLICATE KEY UPDATE totalTrans = values(totalTrans);