[英]How to insert two or more records from a 'unique' field in MySql?
I have these tables我有这些桌子
CREATE TABLE persona(
id INT PRIMARY KEY AUTO_INCREMENT,
nombre VARCHAR(30),
apPaterno VARCHAR(30),
ine VARCHAR(12) unique);
CREATE TABLE cliente( cuenta INT PRIMARY KEY,
saldoapertura DOUBLE,
fechaRegistro DATE,
sucursal VARCHAR(30),
idPersona int,
FOREIGN KEY(idPersona) REFERENCES persona(id));
It is about simulating a bank, in which the identification is unique for each person (ine), I want to know if there is a way to insert a person with different accounts several times.这是关于模拟银行,其中每个人(ine)的标识都是唯一的,我想知道是否有办法多次插入具有不同帐户的人。 Even if the 'unique' clause exists in the (ine) field.
即使 (ine) 字段中存在 'unique' 子句。
The stored procedure is this:存储过程是这样的:
delimiter ##
create procedure sp_aperturaCuenta(
IN p_nombre varchar(30),
in p_apellidoPaterno varchar (30),
in p_ine varchar (12),
in p_cuenta int,
in p_saldoApertura double,
in p_sucursal varchar (30)
)
begin
declare id int;
declare fallo boolean default 0;
declare continue handler for sqlexception
begin
set fallo = 1;
end;
start transaction;
insert into persona (nombre, apPaterno, ine) values (p_nombre,p_apellidoPaterno, p_ine);
set id = last_insert_id();
insert into cliente values (p_cuenta,p_saldoApertura, curdate(), p_sucursal, id );
if fallo = 0 then
commit;
else
rollback;
end if;
end ##
delimiter ;
Here are the calls to the procedure:以下是对该过程的调用:
Call sp_aperturaCuenta('Carlos','Montes','12302002120',1121,1000,'Delta');
Call sp_aperturaCuenta('Carlos','Montes','12302002120',1231,5000,'Delta');
As can be seen, the only difference between one call and another is that the account is different.可以看出,一个呼叫和另一个呼叫之间的唯一区别是帐户不同。 And I can't insert the second.
我不能插入第二个。
To add a second cliente
record for an existing persona
, rename your id
variable to v_id
:要为现有
persona
添加第二条客户记录, v_id
您的id
变量重命名为cliente
:
declare v_id int;
Then try to lookup the persona
by ine
and insert only if you cannot find a record.然后尝试通过
ine
查找persona
并仅在找不到记录时插入。
select id into v_id from persona where ine = p_ine;
if v_id is null then
insert into persona (nombre, apPaterno, ine) values (p_nombre,p_apellidoPaterno, p_ine);
set v_id = last_insert_id();
end if;
insert into cliente values (p_cuenta,p_saldoApertura, curdate(), p_sucursal, v_id );
The unique constraint is a constraint for a reason and RBDMs are excellent at following constraints .唯一约束是有原因的约束,RBDM 非常擅长遵循约束。
As long as you have the unique constraint in your table definition, the column for which the unique constraint is defined for cannot have multiple equal values.只要您的表定义中有唯一约束,为其定义唯一约束的列就不能有多个相等的值。
The only way to bypass the constraint is to remove it, which is not what I'm suggesting if it confronts the requirements for your DB design.绕过约束的唯一方法是删除它,如果它遇到数据库设计的要求,这不是我的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.