Mysql 插入/更新具有外键关系的两个表的存储过程
我不熟悉使用mysql的数据库。我有两个表state和country,其中countryid是state表中的外键。我有一个可以添加state的场景,当添加state时,假设国家是一个新的国家,那么必须在country表上进行插入。我的问题是我正在经历各种文档,我发现不是从java端编写每个查询,而是把所有的东西都组织到存储过程中,这样我就开始做了。 CREATE DEFINER=`pratyush`@`%` PROCEDURE `ADD_STATE`(in statename varchar(45), in countryname varchar(45)) BEGIN declare countryIdd varchar(45); if (!checkNull(statename) AND !checkNull(countryname)) then if exists (select country_id from ems.country where country_name = countryname) then if not exists (select state_id from ems.state where state_name = statename) then select country_id into countryidd from ems.country where country_name = countryname; insert into ems.state(state_name, country_id) values(statename, countryidd); end if; end if; end if; END 如果我出了什么问题,请告诉我。提前谢谢Mysql 插入/更新具有外键关系的两个表的存储过程,mysql,stored-procedures,Mysql,Stored Procedures,我不熟悉使用mysql的数据库。我有两个表state和country,其中countryid是state表中的外键。我有一个可以添加state的场景,当添加state时,假设国家是一个新的国家,那么必须在country表上进行插入。我的问题是我正在经历各种文档,我发现不是从java端编写每个查询,而是把所有的东西都组织到存储过程中,这样我就开始做了。 CREATE DEFINER=`pratyush`@`%` PROCEDURE `ADD_STATE`(in statename varchar(
CREATE DEFINER=`pratyush`@`%` PROCEDURE `ADD_STATE`(in statename varchar(45), in countryname varchar(45))
BEGIN
declare countryIdd varchar(45);
if (!checkNull(statename) AND !checkNull(countryname)) then
if exists (select country_id from ems.country where country_name = countryname) then
if not exists (select state_id from ems.state where state_name = statename) then
select country_id into countryidd from ems.country where country_name = countryname;
insert into ems.state(state_name, country_id) values(statename, countryidd);
end if;
end if;
if not exists (select countryid from country where countryname = @countryname) then
if not exists (select stateid from state where statename = statename) then
insert into ems.country(country_id,country_name) values(countryidd, countryname);
select country_id into countryidd from ems.country where country_name = countryname;
insert into ems.state(state_name, country_id) values(statename, countryidd);
end if;
end if;
end if;
END
对代码做了某些更改。我认为您必须添加另一个条件来检查该国家是否存在,如果不存在,则插入该表。唯一需要做的就是添加一个方法来查找下一个要插入的国家id并将其存储在countryid中。如果countryid字段为int且自动递增,则无需查找id,只需插入countryname,它将自动递增到下一个值。如果答案无效且错误,请提前道歉