使用mySQL中其他表的select结果更新表中的字段

时间:2017-12-23 12:44:24

标签: mysql database count sql-update subquery

我有sum of counts of different columns of same table的后续问题 我想要更新另一个表(B)中的字段(Z),该表还具有ID'使用选择查询的结果(A.COUNT_TOTAL):

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

1 个答案:

答案 0 :(得分:0)

你有ambiguos(和别名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