我希望有一个棘手的SQL语句作为每隔几分钟运行一次的事件。
当前,我正在使用Java,使用3条独立的语句在事务连接中执行顺序。
问:我不知道如何在没有Java的情况下构造这样的SQL语句。如果不可能只有一个SQL语句,那么我想使用事务处理(就像我在Java中使用的那样)并在这些单独的语句中的任何一个失败的情况下进行回滚。 我的案子:
我有3个表格:“ Factory
”,“ Plan
”,“ Machine
”。
我想做以下事情:
1.
WHERE Machines.annualCheck == "TRUE"
SET Machine.status = "IN_ANNUAL_CHECK"
For machines that got updated I need to do the following:
2.1 Update the related factory
WHERE Factory.id == Machine.linkFactoryID
UPDATE Factory.totalActiveMachines = --1
2.2 Delete the upcoming plans that planned to be handled by the related machine
DELETE rows WHERE Plan.willHandleByMachineID = Machine.ID
p.s。我正在使用MySQL
谢谢!
更新:
在遵循Simonare的建议之后,我很累地要做以下事情:
DELIMITER $
CREATE PROCEDURE annualCheck(IN Machine_ID int, IN Factory_ID int)
BEGIN
UPDATE machine_table
SET machine_table.annualCheck = 'IN_ANNUAL_CHECK'
WHERE machine_table.machine_id = Machine_ID;
UPDATE factory_table
SET factory_table.totalActiveMachines = factory_table.totalActiveMachines - 1
WHERE factory_table.factory_id = Factory_ID;
DELETE FROM plan_table WHERE plan_table.assign_to_machine = Machine_ID
END$
DELIMITER $$
BEGIN
SELECT @m_id = machine_id, @f_id = link_factory_id
FROM machine_table
WHERE machine_table.annualCheck = 'TRUE';
END$$
CALL annualCheck(@m_id,@f_id)
我不知道为什么,但是我遇到了语法错误-一个接一个。 这是我第一次使用PROCEDURE和DELIMITER。我做对了吗?
答案 0 :(得分:1)
您可以使用存储过程
delimiter //
CREATE PROCEDURE myProc (IN Machine_ID int)
BEGIN
UPDATE myTable
SET Machine.status = "IN_ANNUAL_CHECK"
WHERE Machines.annualCheck == "TRUE";
Update the related factory
WHERE Factory.id == Machine.linkFactoryID
UPDATE Factory.totalActiveMachines = totalActiveMachines -1;
DELETE FROM Plan WHERE Plan.willHandleByMachineID = Machine_ID;
END//
然后您可以通过mysql
执行它 CALL simpleproc(@a);
或来自Java
答案 1 :(得分:0)
还可以在Machine表上创建触发器,如下所示:
CREATE TRIGGER `TRG_Machines_AfterUpdate` AFTER UPDATE ON `Machine` FOR EACH ROW BEGIN
IF OLD.annualCheck = 'TRUE' AND NEW.annualCheck = 'IN_ANNUAL_CHECK' THEN
UPDATE
Factory
SET
totalActiveMachines = totalActiveMachines - 1
WHERE
id = NEW.linkFactoryID
;
DELETE FROM
Plan
WHERE
willHandleByMachineID = NEW.ID
;
END;
END
因此您可以发出常规更新:
UPDATE Machine SET annualCheck = 'IN_ANNUAL_CHECK' WHERE annualCheck = 'TRUE'