简体   繁体   中英

Insert into a table with a select statement in mysql

I have a table that has training history that has been modified by many different users over the years. This has cause the same training record to be entered twice. I want to create a table that replicates the main table and insert all duplicate records.

What constitutes a duplicate record is if the employee_id, course_code, and completion_date all match.

I can create the duplicate table and I have a select statement that appears to pull duplicates, but it pulls only one of them and I need it to pull both (or more) of them. This is because one person may have entered the training record with a different course name but the id, code, and date are the same so it is a duplicate entry. So by pulling all the duplicates I can validate that that is the case.

Here is my SELECT statement:

SELECT * 
FROM 
    training_table p1
JOIN 
    training_table p2 ON (
        p1.employee_id = p2.employee_id
        AND p1.course_code = p2.course_code
        AND p1.completion.date = p2.completion_date)
GROUP BY p1.ssn;

The query runs and returns what appear to be unique rows. I would like all of the duplicates. And whenever I try to INSERT it into an identical table I get an error stating my column count doesn't match my value count.

Any help would be great.

This will select any duplicate rows for insertion into your new table.

SELECT p1.* 

FROM   training_table p1

JOIN   
       (SELECT employee_id, course_code, completion_date
        FROM   training_table 
        GROUP BY employee_id, course_code, completion_date
        HAVING COUNT(*) > 1
       ) dups 
        ON  p1.employee_id = dups.employee_id
        AND p1.course_code = dups.course_code
        AND p1.completion_date = dups.completion_date
;

Try to use CROSS JOIN (Cartesian Product Join) instead JOIN only. For insert try INSERT INTO TABLE (column1, column2, column3) SELECT column1, column2, column3 FROM TABLE; in same order.

Thanks for the help. I had discovered the answer shortly after I posted the question (even though I had looked for the answer for over an hour :) ) Here is what I used:

 SELECT  *
    FROM    training_table mto
    WHERE   EXISTS
            (
    SELECT  1
    FROM    training_table mti


    WHERE   mti.employee_id = mto.employee_ie
    AND mti.course_code = mto.course_code
    AND mti.completion_date = mto.completion_date
            LIMIT 1, 1
            )

I just added the INSERT statement and it worked. Thanks.

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