使用mySQL中另一个表中的select结果更新表中的字段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用mySQL中另一个表中的select结果更新表中的字段相关的知识,希望对你有一定的参考价值。
我有一个sum of counts of different columns of same table的后续问题我想更新另一个表(B)中的字段(Z),该表还具有选择查询结果(A.COUNT_TOTAL)的“ID”:
SELECT A.ID, SUM(A.COUNTS) AS COUNT_TOTAL
FROM
(
SELECT X AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY X
UNION ALL
SELECT Y AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY Y
) A
GROUP BY A.ID
ORDER BY A.ID;`
我尝试了以下声明,(但得到一个模糊的错误信息):
UPDATE B
INNER JOIN (
SELECT A.ID, SUM(A.COUNTS) AS COUNT_TOTAL
FROM
(
SELECT X AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY X
UNION ALL
SELECT Y AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY Y
) A
GROUP BY A.ID) as A on B.ID = A.ID
SET B.Z = A.COUNT_TOTAL
答案
你有不明确的(和别名A的错误引用..你对不同的别名使用两次相同的名称)尝试为不同的子查询使用不同的别名,例如:
UPDATE B
INNER JOIN (
SELECT A.ID, SUM(A.COUNTS) AS COUNT_TOTAL
FROM
(
SELECT X AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY X
UNION ALL
SELECT Y AS ID, COUNT(*) AS COUNTS FROM TABLE1 GROUP BY Y
) A
GROUP BY A.ID) T on B.ID = T.ID
SET B.Z = T.COUNT_TOTAL
以上是关于使用mySQL中另一个表中的select结果更新表中的字段的主要内容,如果未能解决你的问题,请参考以下文章