我不想让触发器删除具有最低ID的行,如果它是重复出现的话。通过重复我的意思是数字和用户名在两行中是相同的。
例如
ROW1:ID:1,Nr:1,UN:MVJ和
第2行:ID:2,Nr:1,UN:MVJ
这些是反复发生的,但如果'Nr'或'UN'不同,它们就不会。
但正如标题所解释的那样,MYSQL无法做到这一点,至少我已经制作了我的SQL语句。 我愿意以另一种方式解决问题。
Drop trigger no_double_reservations;
DELIMITER !!
CREATE TRIGGER no_double_reservations
AFTER INSERT ON tilmeldte
FOR EACH ROW BEGIN
IF(
SELECT COUNT(*)
FROM tilmeldte
WHERE (kursus_nr, username)
IN (
SELECT kursus_nr, username
FROM tilmeldte
GROUP BY kursus_nr, username
HAVING COUNT(*) = 2
) = 2
)
THEN
DELETE FROM tilmeldte
Where tilmeldingsid = (
Select MIN(`tilmeldingsid`)
FROM tilmeldte
WHERE (kursus_nr, username)
IN (
SELECT MIN(kursus_nr), username
FROM tilmeldte
GROUP BY kursus_nr, username
HAVING COUNT(*) = 2
)
);
END IF;
END!!
DELIMITER ;
我希望你能提供帮助。
答案 0 :(得分:0)
由于您还没有给出任何表定义,这里有一个逻辑如何在MySQL中完成此任务。
创建带有您的用户名和kursus_id的存储过程 检查用户名是否已存在 如果是>删除并插入新ID 如果没有>只需插入新记录并发回消息
代码中的就像是。
CREATE PROCEDURE `SP_NEW_RESERVATION` (in iUsername varchar(50), in iKursus_id int)
BEGIN
DECLARE EXIT HANDLER for sqlexception
BEGIN
rollback;
SELECT 'False' as Result, 'Some error description or diagnose description from mysql' as `Description`;
END;
Start Transaction;
SET @mExists := (SELECT ID from tbl_yourTable where ((kursus_id = iKursus_id) and (username like iUsername)));
if (length(coalesce(@mExists,'')) <> 0) then
-- username does not exists so you can continue with insert a new reservation
insert into tbl_yourTable and continue here
-- send back message
SELECT 'True' as Result, 'New record inserted') as `Description`;
ELSE
-- username exists already and the id would be saved in mExists so delete the id and continue with your insert_method
Delete from Tbl_yourtable where id = @mExists something ligke that;
insert into tbl_yourtable .....
-- you can send back a message like
SELECT 'True' as Result, concat('Old record(', @mExists, ') Deleted and new record inserted') as `Description`;
end if;
Commit;
END
以上代码不完整。要执行此代码,您需要更正插入和删除命令。然后只需调用类似的程序。
call SP_NEW_RESERVATION('KrishKm', 2);
如果用户名&#39; KrishKm&#39;已存在,您将收到消息,如:
True,旧记录(10)已删除并插入新记录。
如果没有,你会得到回复信息:
True, New record inserted.
如果出现任何问题,您会收到消息:
False, 'Some error description or diagnose description from mysql'
祝你好运。