我有几个insert语句,我只想在它们为真时执行它们。
下面是我的例子:
START TRANSACTION;
INSERT INTO fields (field_name, control_type_id, needs_approval)
VALUES
('Array Photos', 3, 0);
INSERT INTO field_to_job_type (field_id, job_type_id, sequence_number, parent_id)
VALUES
(last_insert_id(), (SELECT job_type_id FROM job_types WHERE job_type_name = 'Cash'), 1, (SELECT field_id FROM fields where field_name = 'Photo Pack'));
COMMIT;
现在,我只想在这个查询只有一个结果时运行第二个查询:
SELECT job_type_id FROM job_types WHERE job_type_name = 'Cash'
。如果该查询返回2个结果,我将放弃该事务。
有可能吗?我试过的东西:
START TRANSACTION;
INSERT ...;
INSERT ...;
IF(SELECT count(job_type_name) FROM job_types WHERE job_type_name = 'Cash') = 1, 'COMMIT', 'ROLLBACK');
显然,这不起作用。
最佳答案
在变量中选择计数,然后在比较中使用它。
DECLARE total_row INT DEFAULT 0
START TRANSACTION;
INSERT INTO fields (field_name, control_type_id, needs_approval)
VALUES ('Array Photos', 3, 0);
SELECT count(job_type_name) FROM job_types WHERE job_type_name = 'Cash' INTO total_rows;
IF total_rows =2 THEN
ROLLBACK;
ELSE
INSERT INTO field_to_job_type (field_id, job_type_id, sequence_number, parent_id)
VALUES (last_insert_id(), (SELECT job_type_id FROM job_types WHERE job_type_name = 'Cash'), 1, (SELECT field_id FROM fields where field_name = 'Photo Pack'));
COMMIT;
END IF;