SQL Error 1452: Cannot add or update child - mysql

Create table Course(CourseID char(5),CourseDesc varchar(25),CourseType char(9),SemNo int(1),FacID char(4) default 0);
alter table Course add primary key(CourseID);
alter table Course add foreign key(FacID) references Faculty1(FacID);
here FacID is the foreign key which the primary key of the Faculty
when i am inserting values, i try insert this values
insert into Course(CouseID,CourseDesc,CourseType,SemNo,FacID) values ('EE025','Digital Logic Circuits','Theory','4','');
But,this produces sql error 1452 ,please resolve it .

You misspelled CourseID in your insert:
insert into Course(CouseID,CourseDes...
Should be:
insert into Course(CourseID,CourseDes...

Have you confirmed that you have a row in Faculty1 with FacID = 0?
insert into Faculty1 (FacID /* other columns */) values (0 /*, other values*/ );
insert into Course(CourseID,CourseDesc,CourseType,SemNo,FacID) values ('EE025','Digital Logic Circuits','Theory',4,0);
If you want to insert a blank value ('') then you need to have an empty string value in Faculty1.FacID. Otherwise you could properly indicate a '0'.
create table Faculty1(
FacID char(4) not null primary key
);
insert into faculty1 values (0);
create table Course(
CourseID char(5) not null
, CourseDesc varchar(25)
, CourseType char(9)
, SemNo int
, FacID char(4) not null default 0
/* specify not null to use default when value not inserted */
);
alter table Course add primary key(CourseID);
alter table Course add foreign key(FacID) references Faculty1(FacID);
/* inserting `''` instead of `0` for FacId results in an error */
begin try;
insert into Course(CourseID,CourseDesc,CourseType,SemNo,FacID) values
('EE025','Digital Logic Circuits','Theory','4','');
end try
begin catch
select error_message();
end catch;
/* inserting `0` for FacId = no error*/
insert into Course(CourseID,CourseDesc,CourseType,SemNo,FacID) values
('EE025','Digital Logic Circuits','Theory',4,'0');
select * from Course;
/* inserting without specifying FacId uses default*/
insert into Course(CourseID,CourseDesc,CourseType,SemNo) values
('EE026','Digital Logic Circuits','Theory',4);
select * from Course;
rextester demo: http://rextester.com/ZYGWRX20984

Related

Trigger dows not let me insert data in mysql

i am trying to get used to triggers. I created a small database and a trigger. When i go to insert something in ship category it does not let me do it.If i drop the trigger with the same commend i can insert values at the table. I get this error: #1048 - Column 'IMO' cannot be null
My trigger code is:
/*ship insert*/
DELIMITER //
CREATE TRIGGER `ship_insert_logs`
AFTER INSERT ON `ship`
FOR EACH ROW
BEGIN
DECLARE ship_IMO INTEGER;
SET ship_IMO=new.IMO;
INSERT INTO ship_logs VALUES (null, concat('A new row is inserted with IMO ', ship_IMO, 'at',
date_format(now(), '%d-%m-%y %h:%i:%s %p')));
END //
DELIMITER ;
and ship table is:
CREATE TABLE ship(
department_id INTEGER NOT NULL,
IMO BIGINT PRIMARY KEY NOT NULL,
Latitude DOUBLE PRECISION NOT NULL,
Longitude DOUBLE PRECISION NOT NULL,
current_speed DOUBLE PRECISION NOT NULL,
heading VARCHAR (30),
status VARCHAR(30),
FOREIGN KEY(department_id) REFERENCES department (department_id) ON UPDATE CASCADE
);
while ship_logs table is:
CREATE TABLE ship_logs(
IMO BIGINT PRIMARY KEY NOT NULL,
audit_description VARCHAR(500)
);

Cannot create trigger

I am just want to create after insert trigger to insert a new row in history table. Why am I getting an error when I run the query?
orders
create table orders
(
id int auto_increment
primary key,
id_user int not null,
picture_name varchar(100) not null,
time date not null,
constraint FK_USER
foreign key (id_user) references stef.users (id)
)
;
create index FK_USER_idx
on orders (id_user)
;
history
create table history
(
id int auto_increment
primary key,
id_order int not null,
id_action int not null,
time date not null,
constraint FK_ORDER
foreign key (id_order) references stef.orders (id),
constraint FK_ACTION
foreign key (id_action) references stef.actions (id)
)
;
create index FK_ORDER_idx
on history (id_order)
;
create index FK_ACTION_idx
on history (id_action)
;
my trigger...
CREATE TRIGGER orders_AFTER_INSERT
AFTER INSERT ON stef.orders
FOR EACH ROW
BEGIN
INSERT INTO history('id_order', 'id_action', 'time')
VALUES (NEW.id, 1, NOW());
END;
I am just want to create after insert trigger to insert a new row in history table. Why am I getting an error when I run the query?
Try this
DELIMITER $$
CREATE TRIGGER orders_AFTER_INSERT
AFTER INSERT ON stef.orders
FOR EACH ROW
BEGIN
INSERT INTO history(`id_order`, `id_action`, `time`)
VALUES (NEW.id, 1, NOW());
END$$
DELIMITER ;
You need to temporarily override the delimiter so MySQL can differentiate between the end of a statement within the body of a trigger (or procedure, or function) and the end of the body.
Edit: Single quotes (') are only ever used to denote string values, for field names use the ` (or in some configurations the ")
CREATE TRIGGER orders_AFTER_INSERT
AFTER INSERT ON stef.orders
FOR EACH ROW
BEGIN
INSERT INTO stef.history()
VALUES (null, NEW.id, 1, NOW());
END

inserting values from arrays in mysql

I have multiple user_roles. Each user_role has multiple privileges and each privileges has multiple values. I need to create a procedure with user_role_name,description,priviliges_fk(array),values(arrayofstring) as inputs.
This is the procedure I have written.
DELIMITER $$
DROP PROCEDURE IF EXISTS `save_role`$$
CREATE DEFINER=`event_admin`#`%` PROCEDURE `save_role`(IN p_role_name INT,
IN p_description INT,
IN p_privilege_fk INT(),
IN p_values VARCHAR(1000)
)
BEGIN
DECLARE i int default 0;
DECLARE V_ROLE_FK int;
DECLARE counter INT DEFAULT 0;
INSERT INTO ROLE (ROLE_NAME,DESCRIPTION) VALUES(p_role_name,p_description);
SELECT ROLE_PK INTO V_ROLE_FK FROM ROLE WHERE ROLE_NAME=p_role_name AND DESCRIPTION=p_description;
simple_loop:LOOP
SET counter = counter + 1;
INSERT INTO ROLE_PRIVILEGE_BRIDGE (ROLE_FK,PRIVILEGE_FK,VALUE) VALUES(V_ROLE_FK,p_privilege_fk(i),p_values);
END LOOP simple_loop;
END;
You can't. There are two workarounds that would work
Call the procedure one time per element in the array
Concatenate the array elements into one string separated by something (ie |, ;, :) and then split that string internally in the procedure.
I would go with the first alternative. It's cleaner, easier to understand and easier to test.
I'd suggest you to use AUTO_INCREMENT option for primary keys, it will help to work with them. Then use auto-incremented primary key values to insert new rows into a child table - one by one, not using array as a string parameter.
For example (data is simplified):
CREATE TABLE ROLE(
ID INT(11) NOT NULL AUTO_INCREMENT,
ROLE_NAME INT,
DESCRIPTION INT,
PRIMARY KEY (ID)
)
ENGINE = INNODB;
CREATE TABLE ROLE_PRIVILEGE_BRIDGE(
ID INT(11) NOT NULL AUTO_INCREMENT,
PRIVILEGE_FK INT(11) DEFAULT NULL,
VALUE INT(11) DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK FOREIGN KEY (PRIVILEGE_FK) REFERENCES ROLE (ID)
)
ENGINE = INNODB;
INSERT INTO ROLE(ROLE_NAME, DESCRIPTION) VALUES(1, 1);
SET #new_id = LAST_INSERT_ID();
INSERT INTO ROLE_PRIVILEGE_BRIDGE(PRIVILEGE_FK, VALUE) VALUES (#new_id, 1);
INSERT INTO ROLE_PRIVILEGE_BRIDGE(PRIVILEGE_FK, VALUE) VALUES (#new_id, 2);
INSERT INTO ROLE_PRIVILEGE_BRIDGE(PRIVILEGE_FK, VALUE) VALUES (#new_id, 3);

INSERT statement for MySQL table

CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (ID=4,Name='xxx')
or
INSERT INTO MyTable (Name) VALUES (Name='xxx')
The problem is that both INSERT statements produce the entry (4,0). Why 0 instead of "xxx"?
UPDATE: Primary key changed.
This should do the job :
INSERT INTO MyTable (ID, Name) VALUES (4, 'xxx')
I'm pretty sure it would be something like this, instead...
INSERT INTO MyTable (Name) VALUES ('xxx')
No need for the Name= part, since you've already specified which column you wish to insert into with the first (Name) definition.
Because the expression Name='xxx' is false, hence evaluates as zero.
You use the column=expression method use in on duplicate key update clauses as described here, not in the "regular" section of inserts. An example of that:
insert into mytable (col1,col2) values (1,2)
on duplicate key update col1 = col1 + 1
You should be using the syntax:
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
Is that syntax of Name='xxx' valid? Never seen it before, i assume it is seeing it as an unquoted literal, trying to convert it to a number and coming up with 0? I'm not sure at all
Try this:
INSERT INTO MyTable (Name) VALUES ('xxx')
This is because you should mention the name of the column in the values part. And also because you do not define you primary key correctly (airlineID is not part of the field list)
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
INSERT INTO MyTable (Name) VALUES ('xxx')
Try this
INSERT INTO MyTable (ID,Name) VALUES (4,xxx)
For more Info just visit this link

Insert on duplicate key causing problems in auto increment field

CREATE TABLE IF NOT EXISTS `foo` (
`foo_id` INT NOT NULL AUTO_INCREMENT ,
`unique` CHAR(255) NULL ,
`not_unique` CHAR(255) NULL ,
PRIMARY KEY (`foo_id`) ,
UNIQUE INDEX `unique_UNIQUE` (`unique` ASC) )
ENGINE = InnoDB;
This is the table.
INSERT INTO foo (`unique`,`not_unique`) VALUES ('John','Doe')
ON DUPLICATE KEY UPDATE `foo_id`=LAST_INSERT_ID(`foo_id`);
SELECT LAST_INSERT_ID();
LAST_INSERT_ID here returns 1. That is correct.
INSERT INTO foo (`unique`,`not_unique`) VALUES ('John','Doe')
ON DUPLICATE KEY UPDATE `foo_id`=LAST_INSERT_ID(`foo_id`);
SELECT LAST_INSERT_ID();
LAST_INSERT_ID here returns 1. That is correct.
INSERT INTO foo (`unique`,`not_unique`) VALUES ('Jane','Doe')
ON DUPLICATE KEY UPDATE `foo_id`=LAST_INSERT_ID(`foo_id`);
SELECT LAST_INSERT_ID();
LAST_INSERT_ID here returns 3. Why? I was hoping it to be 2. If this is a bug, is there a workaround for it?
The id was taken at the beginning of the attempted insert, and was discarded on failure.