尝试将值从一个 table 插入到另一个未找到代理键匹配项的位置

Trying to insert values from one table to another where a surrogate key match is not found

我正在尝试模拟完整的外部联接,将两个 table 相互比较。 batch_import table 包含需要插入的记录,前提是它们不存在于员工 table 中。为此,我尝试了以下查询:

INSERT INTO employees (forename, surname, employersId, custom_corpore_headOffice, contractId)
SELECT firstname, surname, employeenumber, dob, store, contractId
FROM batch_import
LEFT JOIN employees ON batch_import.employeenumber = employees.employersId AND batch_import.contractId = employees.contractId
UNION ALL
SELECT forename, surname, employersId, custom_corpore_headOffice, contractId
FROM batch_import RIGHT JOIN employees ON batch_import.employeenumber = employees.employersId AND batch_import.contractId = employees.contractId
WHERE batch_import.employeenumber IS NULL AND batch_import.contractId IS NULL
                       ";

然而,当我运行此查询时,我从 mysql 收到消息:错误 1137 (HY000):无法重新打开 table:'batch_import'

我猜这是我的 UNION ALL 的逻辑不正确。有人可以帮我找到解决方案吗?

EDIT:: 我试过这个查询,它从最后一条记录开始一直在 table 上添加记录。我也试过:

                    INSERT INTO employees (forename, surname, employersId, dateOfBirth, custom_corpore_headOffice, contractId)
                SELECT firstname, batch_import.surname, employeenumber, dob, store, batch_import.contractId
                FROM batch_import
                LEFT JOIN employees ON batch_import.employeenumber = employees.employersId AND batch_import.contractId = employees.contractId
                UNION
                SELECT firstname, batch_import.surname, employeenumber, dob, store, batch_import.contractId
                FROM batch_import RIGHT JOIN employees ON batch_import.employeenumber = employees.employersId AND batch_import.contractId = employees.contractId;

但仍然无济于事。它不会忽略存在的内容,而是简单地将所有内容写入 table.

的末尾

也尝试过:INSERT INTO employees (forename, surname, employersId, dateOfBirth, custom_corpore_headOffice, contractId) SELECT firstname, batch_import.surname, employeenumber, dob, store, batch_import.contractId FROM batch_import LEFT JOIN employees ON employees.employersId = NULL;

选项 1

INSERT INTO employees (forename, surname, employersId, custom_corpore_headOffice, contractId)
SELECT firstname, surname, employeenumber, dob, store, contractId
FROM batch_import
WHERE NOT EXISTS (Select 1 From employees where batch_import.employeenumber = employees.employersId AND batch_import.contractId = employees.contractId)

选项 2

INSERT INTO employees (forename, surname, employersId, custom_corpore_headOffice, contractId)
SELECT firstname, surname, employeenumber, dob, store, contractId
FROM batch_import
LEFT JOIN employees ON batch_import.employeenumber = employees.employersId AND batch_import.contractId = employees.contractId
WHERE employees.employersId is NULL