加入两个表并更新MySql中的第三个表

时间:2015-11-27 14:36:25

标签: mysql

我正在尝试加入两个表tblN1tblN2来获取用户的总访问次数并更新第三个表tblNCC但没有成功,因为我有错误:

[Err] 1054 - Unknown column 't.UserN1' in 'on clause'

我不明白这个错误......列t.UserN1在Select sql query中。

问题可能是Union All语法?

我的代码如下,请帮助我。

提前非常感谢你。

UPDATE tblNCC AS CC
JOIN (
    SELECT
        sum(total) AS Total
    FROM
        (
            SELECT
                COUNT(*) AS Total,
                UserN1
            FROM
                `tblN1`
            WHERE
                UserN1 IN ('7047505')
            AND dateN1 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
            AND CURDATE()
            UNION ALL
                SELECT
                    COUNT(*) AS Total,
                    UserN2
                FROM
                    `tblN2`
                WHERE
                    UserN2 ('7047505')
                AND dateN2 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
                AND CURDATE()
        ) AS t
) AS q ON t.UserN1 = CC.UserNcc
SET CC.Total = t.Total;
[Err] 1054 - Unknown column 't.UserN1' in 'on clause'

1 个答案:

答案 0 :(得分:0)

t不在范围内。它在q内。

你可能意味着这样的事情:

UPDATE tblNCC AS CC
JOIN (
    SELECT
        username,
        sum(total) AS Total
    FROM
        (
            SELECT
                COUNT(*) AS Total,
                UserN1 as username
            FROM
                `tblN1`
            WHERE
                UserN1 IN ('7047505')
            AND dateN1 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
            AND CURDATE()
            UNION ALL
                SELECT
                    COUNT(*) AS Total,
                    UserN2 as username
                FROM
                    `tblN2`
                WHERE
                    UserN2 ('7047505')
                AND dateN2 BETWEEN MAKEDATE(YEAR(CURDATE()), 1)
                AND CURDATE()
        ) AS t
) AS q ON q.username = CC.UserNcc
SET CC.Total = q.Total;