如果存在第一个字段(主键)或在mysql中插入新行(在单个查询中),如何更新第二个字段?
INSERT INTO employee_lu(employeeId, employee_dept,CREATED_TS)
SELECT * FROM (SELECT "E1" AS cd, "DGSDFGSF" AS dept, NOW() AS created_ts) AS temp
WHERE NOT EXISTS (SELECT 1 FROM employee_lu WHERE employeeId = "E1" and employee_dept = "DGSDFGSF")LIMIT 1
or if exists (SELECT 1 FROM employee_lu WHERE employeeId = "E1" )LIMIT 1
update employee_lu set employee_dept = "CCCC" WHERE employeeId = "E1"
如果员工身份和给定部门都存在,则不做任何事情。如果员工ID与不同的部门存在,则用新部门(给定)更新旧部门。如果两者都不存在则插入新行。
有人可以告诉我如何在单个查询中执行此操作?如果我只是插入但没有工作,如果添加更新,它工作正常。
只需插入=
INSERT INTO employee_lu(employeeId, employee_dept,CREATED_TS)
SELECT * FROM (SELECT "F1" AS cd, "DGSDFGSF" AS description, NOW() AS created_ts) AS temp
WHERE NOT EXISTS (SELECT 1 FROM employee_lu WHERE employeeId = "F1" and employee_dept = "DGSDFGSF")LIMIT 1;
但是我需要更新该字段是否与我们正在搜索的字段具有不同的值。有人可以告诉我该怎么做。
我的表格如下:
CREATE TABLE `employee_lu` (
`employeeId` varchar(10) NOT NULL DEFAULT '',
`employee_dept` varchar(256) NOT NULL DEFAULT '',
`CREATED_TS` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`LAST_UPDATED_TS` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`employeeId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;