如果表B.column小于,则Mysql将表A中的记录插入表B.

时间:2013-04-10 23:55:37

标签: mysql sql join relational-database

**Employee**

PK empId
firstName
lastName
isRegularEmp


**Employee_Training**

PK FK empId
PK FK trainingId
logId


**Training**

PK TrainingId
date
specialEmployeesNeeded
regularEmployeesNeeded
FK roomId

我试图在特定日期之前将所有员工插入employee_training表。除了我有超过特殊雇员/常规雇员字段值的必要金额外,它的工作原理。

例如,我在员工表中有200名普通员工和100名普通员工,但我只需要按照培训表中的规定插入35名特殊员工和5名重新组织员工。

我试过HAVING但是它一直在抛出错误的未知列。请帮助,我尝试插入一种类型的员工,但它仍然无效

INSERT INTO EMPLOYEE_TRAINING(empId, trainingId)


SELECT E.empId , T.TrainingId


FROM EMPLOYEE E, TRAINING T

WHERE T.`date` = "2013-4-20" 

AND E.isRegularEmp = false

HAVING COUNT(E.empId) <= regularEmployeesNeeded

我无法发布我的错误,因为我没有足够的积分。所以,请光临我

2 个答案:

答案 0 :(得分:1)

regularEmployees不是任何表中的列,也不是在查询中的任何位置定义的。试试

INSERT INTO EMPLOYEE_TRAINING(empId, trainingId)

SELECT E.empId , T.TrainingId

FROM EMPLOYEE E, TRAINING T

WHERE T.`date` = "2013-4-20"

AND E.isRegularEmp = false

HAVING COUNT(E.empId) <= (select count(*) from EMPLOYEE where isRegularEmp=true )

答案 1 :(得分:0)

isRegularEmp条件的展示位置不正确。它应该放在WHERE子句中。

INSERT INTO EMPLOYEE_TRAINING(empId, trainingId)

SELECT E.empId , T.TrainingId

FROM EMPLOYEE E, TRAINING T

WHERE T.`date` = "2013-4-20"

AND E.isRegularEmp = false

HAVING COUNT(E.empId) <= regularEmployees

编辑:正如Michael Benjamin的回答所指出的那样,regularEmployees不是未定义的字段。您需要SELECT COUNT正式员工。

INSERT INTO EMPLOYEE_TRAINING(empId, trainingId)

SELECT E.empId , T.TrainingId

FROM EMPLOYEE E, TRAINING T

WHERE T.`date` = "2013-4-20"

AND E.isRegularEmp = false

HAVING COUNT(E.empId) <= (SELECT COUNT(*) FROM EMPLOYEE WHERE isRegularEmp = true)