Insert into a table from multiple table(MySql)

Issue

insert ignore into user_login_history 
        (`created_at`,`updated_at`,`created_by`,
         `updated_by`,`USER_ID`,`TENANT`,
         `LAST_LOGIN`,`deleted`,`published`)
values(
    (SELECT 
        a.created_at,
        a.updated_at,
        a.created_by,
        a.updated_by,
        user.id,
        a.tenant,
        a.created_at,
        b'0',
        b'1'
    FROM
    (SELECT audit_log_summary.*
     FROM audit_log_summary, (SELECT 
        user, MAX(created_at) AS created_at, tenant
    FROM
        audit_log_summary
    WHERE
        audit_log_summary.REVISION_TYPE = 'LOGGED_IN'
    GROUP BY user , TENANT) max_user
    WHERE
        audit_log_summary.user = max_user.user
            AND audit_log_summary.tenant = max_user.tenant
            AND audit_log_summary.created_at = max_user.created_at) a
        INNER JOIN
    user ON a.user = user.email));

error i am getting :

Error Code: 1136. Column count doesn’t match value count at row 1

basically I have 3 tables i want to populate data in one table fetching the data from other two..

Table to be populated: user_login_history
Tables From which datas are fetched: audit_log_summary & user

Solution

You have to remove VALUES from the clause, so instead of using INSERT INTO VALUES, use INSERT INTO SELECT FROM. Maybe SELECT audit_log_summary.* you should select the needed columns only. In your select you are selecting a.created_at twice, check if it is what you want.
Maybe this will help:

insert ignore into user_login_history  (`created_at`,
                                        `updated_at`,
                                        `created_by`, 
                                        `updated_by`,
                                        `USER_ID`,
                                        `TENANT`,
                                        `LAST_LOGIN`,
                                        `deleted`,
                                        `published`)
(SELECT 
        a.created_at,
        a.updated_at,
        a.created_by,
        a.updated_by,
        user.id,
        a.tenant,
        a.created_at,
        b'0',
        b'1'
 FROM
    (SELECT audit_log_summary.*
     FROM audit_log_summary, (SELECT 
        user, MAX(created_at) AS created_at, tenant
    FROM
        audit_log_summary
    WHERE
        audit_log_summary.REVISION_TYPE = 'LOGGED_IN'
    GROUP BY user , TENANT) max_user
    WHERE
        audit_log_summary.user = max_user.user
            AND audit_log_summary.tenant = max_user.tenant
            AND audit_log_summary.created_at = max_user.created_at) a
        INNER JOIN
    user ON a.user = user.email));

Answered By – Ergest Basha

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published