简体   繁体   中英

Join two tables and update third table in MySql

I am trying to join two tables tblN1 and tblN2 to get the number of total access for user and update the third table tblNCC without success because I have error:

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

I don't understand this error ... the column t.UserN1 is in Select sql query.

Maybe the problem is the Union All syntax ?

My code below, please help me.

Thank you so much in advance.

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'

t is not in the scope. it's inside q .

You probably mean something like this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM