MySql - can BEFORE INSERT TRIGGER insert into 2 columns? - mysql

Can this trigger be changed so that the sortorder table gets 2 column values (sortOrderId, sortOrder) inserted?
How is the value of sortOrder found?
If it is known and can be inserted into image table then can it also be inserted into the sortorder table?
-- Trigger DDL Statements
DELIMITER $$
USE `nextcart`$$
CREATE
DEFINER=`root`#`localhost`
TRIGGER `nextcart`.`insert_sortorderid`
BEFORE INSERT ON `nextcart`.`image`
FOR EACH ROW
BEGIN
INSERT INTO sortorder SET sortOrderId = NULL, sortOrder = NEW.sortOrder;
SET NEW.sortOrderId = (SELECT LAST_INSERT_ID());
END;
$$
CREATE TABLE sortorder:
delimiter $$
CREATE TABLE `sortorder` (
`sortOrderId` int(11) NOT NULL AUTO_INCREMENT,
`sortOrder` tinyint(4) NOT NULL,
PRIMARY KEY (`sortOrderId`),
KEY `sort_order` (`sortOrderId`,`sortOrder`),
CONSTRAINT `fk_sortOrderId` FOREIGN KEY (`sortOrderId`) REFERENCES `image` (`imageId`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8$$
CREATE TABLE image:
delimiter $$
CREATE TABLE `image` (
`imageId` int(11) NOT NULL AUTO_INCREMENT,
`imageFileName` varchar(45) DEFAULT NULL,
`imagePath` varchar(255) DEFAULT NULL,
`imageTitle` varchar(100) DEFAULT NULL,
`imageAlt` varchar(100) DEFAULT NULL,
`imageWidth` int(11) DEFAULT NULL,
`imageHeight` int(11) DEFAULT NULL,
`classId` int(11) DEFAULT NULL,
`imageSizeId` tinyint(4) NOT NULL,
`isImageEnabled` bit(1) DEFAULT b'0',
`sortOrderId` int(11) DEFAULT NULL,
PRIMARY KEY (`imageId`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8$$
ERROR MESSAGE:
Error 1054: Unknown column 'sortOrder' in 'NEW' SQL Statement:
CREATE TRIGGER insert_sortorderid BEFORE INSERT ON image FOR EACH
ROW BEGIN INSERT INTO nextcart.sortorder SET sortOrderId = NULL,
sortOrder = NEW.sortOrder; SET NEW.sortOrderId = ( SELECT
LAST_INSERT_ID()); END; Error when running failback script. Details
follow. Error 1050: Table 'image' already exists SQL Statement: CREATE
TABLE image ( imageId int(11) NOT NULL AUTO_INCREMENT,
imageFileName varchar(45) DEFAULT NULL, imagePath varchar(255)
DEFAULT NULL, imageTitle varchar(100) DEFAULT NULL, imageAlt
varchar(100) DEFAULT NULL, imageWidth int(11) DEFAULT NULL,
imageHeight int(11) DEFAULT NULL, classId int(11) DEFAULT NULL,
imageSizeId tinyint(4) NOT NULL, isImageEnabled bit(1) DEFAULT
b'0', sortOrderId int(11) DEFAULT NULL, PRIMARY KEY (imageId)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

There is no column named sortOrder in the image table.
So, the reference to NEW.sortOrder (on the insert statement in the trigger) is invalid.
To answer your first question: No. Since there is no value supplied for that in the INSERT statement (which fires the BEFORE INSERT TRIGGER), you don't really have a source for that value.
The easy option is to provide a default value for it.
If you want to supply a value for the sortOrder column, then one option is to add a sortOrder column to the image table, and then the value can be supplied in the INSERT INTO image statement. Then it would available in the trigger.
(The purpose of the sortorder table is not at all clear.)

Related

How to make a trigger in mysql that I update the data of a bitmap when ejecting another trigger from insert

I am working on a project in php where I have to do audit of the database of all the changes. I have a table where the table is stored changes of a person table
CREATE TABLE `personas` (
`cedula` varchar(13) NOT NULL,
`nombres` varchar(30) NOT NULL,
`apellidos` varchar(20) NOT NULL,
`sexo` varchar(10) NOT NULL,
`telefono` varchar(20) NOT NULL,
`direccion` text NOT NULL,
`fnacimiento` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
And I have a users table
CREATE TABLE `usuarios` (
`id` int(10) NOT NULL,
`correo` varchar(80) DEFAULT NULL,
`usuario` varchar(10) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`last_session` datetime DEFAULT NULL,
`activacion` int(15) NOT NULL DEFAULT '0',
`token` varchar(40) NOT NULL,
`token_password` varchar(100) NOT NULL,
`password_request` int(11) NOT NULL DEFAULT '0',
`id_tipo` varchar(20) DEFAULT NULL,
`usuarios_cedula` varchar(13) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The logbook is as follows
CREATE TABLE `bitacorapersonas` (
`idBitacora` int(20) NOT NULL,
`accion` varchar(20) NOT NULL,
`fecha` datetime NOT NULL,
`cedUsuario` varchar(20) DEFAULT NULL,
`nombreUsuario` varchar(13) NOT NULL,
`tipoUsuario` varchar(15) NOT NULL,
`cedula` varchar(13) NOT NULL,
`nombreNuevo` varchar(25) DEFAULT NULL,
`nombreViejo` varchar(20) DEFAULT NULL,
`apellidoNuevo` varchar(30) NOT NULL,
`apellidoViejo` varchar(30) DEFAULT NULL,
`sexoNuevo` varchar(10) NOT NULL,
`sexoViejo` varchar(10) DEFAULT NULL,
`telefonoNuevo` varchar(15) NOT NULL,
`telefonoViejo` varchar(15) DEFAULT NULL,
`direccionNuevo` varchar(40) NOT NULL,
`direccionViejo` varchar(40) DEFAULT NULL,
`fnacimientoNuevo` date NOT NULL,
`fnacimientoViejo` date DEFAULT NULL,
`usuarioNuevo` varchar(15) NOT NULL,
`correoNuevo` varchar(15) NOT NULL,
`correoViejo` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
In the people table and the user table I have a trigger for each one. But I am presenting the following: when I enter a person the data are divided into two rows apart instead of placing them in a single (for being the same person that I am entering)
The triggers are as follows
CREATE TRIGGER `Personas_AInsertar` AFTER INSERT ON `personas`
FOR EACH ROW
INSERT INTO bitacorapersonas (accion,fecha,cedUsuario, nombreUsuario,tipoUsuario,cedula,nombreNuevo,apellidoNuevo,sexoNuevo,telefonoNuevo,direccionNuevo,fnacimientoNuevo)
VALUES ('Inserto',NOW(),#identificador,#identificador2,#identificador3,NEW.cedula,NEW.nombres,NEW.apellidos,NEW.sexo,NEW.telefono, NEW.direccion,NEW.fnacimiento)
CREATE TRIGGER `Usuarios_AInsertar` AFTER INSERT ON `usuarios`
FOR EACH ROW
INSERT INTO bitacorapersonas (accion,fecha,cedUsuario, nombreUsuario,tipoUsuario, usuarioNuevo,correoNuevo)
VALUES ('Inserto',NOW(),#identificador,#identificador2,#identificador3,NEW.usuario,NEW.correo)
At the time of registering a person I am saving it as follows in the table bitacora
I thought of doing an update trigger in the bitacora so that when user data is logged and the trigger is triggered, the fill is filled with the same fields that are being entered by the person in the fields that are empty on the left side but I have no idea how to do it. If someone can help me or give me some idea how to do it I would appreciate it
Assuming usuarios_cedula is a foreign key to personas.cedula, you can do this in the second trigger:
CREATE TRIGGER `Usuarios_AInsertar` AFTER INSERT ON `usuarios`
FOR EACH ROW
UPDATE bitacorapersonas
SET usuarioNuevo = NEW.usuario, correoNuevo = NEW.correo
WHERE cedula = NEW.usuarios_cedula
This will add these two columns to the row that was inserted by the trigger on personas.
This might do the trick:
Define a key
Change your TRIGGERS to have ON DUPLICATE KEY UPDATE.
And take care that this is running in a transaction.
By having both check on the key, the order of the actions does not have to be guaranteed.
CREATE TRIGGER `Personas_AInsertar` AFTER INSERT ON `personas`
FOR EACH ROW
INSERT INTO bitacorapersonas (accion,fecha,cedUsuario, nombreUsuario,tipoUsuario,cedula,nombreNuevo,apellidoNuevo,sexoNuevo,telefonoNuevo,direccionNuevo,fnacimientoNuevo)
VALUES ('Inserto',NOW(),#identificador,#identificador2,#identificador3,NEW.cedula,NEW.nombres,NEW.apellidos,NEW.sexo,NEW.telefono, NEW.direccion,NEW.fnacimiento) ON DUPLICATE KEY UPDATE....
CREATE TRIGGER `Usuarios_AInsertar` AFTER INSERT ON `usuarios`
FOR EACH ROW
INSERT INTO bitacorapersonas (accion,fecha,cedUsuario, nombreUsuario,tipoUsuario, usuarioNuevo,correoNuevo)
VALUES ('Inserto',NOW(),#identificador,#identificador2,#identificador3,NEW.usuario,NEW.correo) ON DUPLICATE KEY UPDATE ....
If you know that the order of execution is fixed, you can make your live easier by running an INSERT in the first trigger and an UPDATE in the second trigger:
CREATE TRIGGER `Personas_AInsertar` AFTER INSERT ON `personas`
FOR EACH ROW
INSERT INTO bitacorapersonas (accion,fecha,cedUsuario, nombreUsuario,tipoUsuario,cedula,nombreNuevo,apellidoNuevo,sexoNuevo,telefonoNuevo,direccionNuevo,fnacimientoNuevo)
VALUES ('Inserto',NOW(),#identificador,#identificador2,#identificador3,NEW.cedula,NEW.nombres,NEW.apellidos,NEW.sexo,NEW.telefono, NEW.direccion,NEW.fnacimiento) ON DUPLICATE KEY UPDATE....
CREATE TRIGGER `Usuarios_AInsertar` AFTER INSERT ON `usuarios`
FOR EACH ROW
UPDATE bitacorapersonas
SET ....
About security of the actual keeping of a log like this:
If you do not protect your log and your data with a checksum of some kind, the data can still be altered in the log in such a way that you can not determine reality. By adding a checksum methodology, you have easier and more portable proof of tampering with the data.

Unknown column 'dob' in 'field list'

I am getting error Unknown column 'dob' in 'field list'
I know that dob is in my table and have called it many times and in my code the insert is ordered correctly. I am just learning MySQL so I'm completely lost
insert into users (userid, firstname, username,dob)
values ('gg', 'greg', 'greg2', '1980-01-01');
here is the table I am trying to insert it into.
CREATE TABLE `users` (
`userid` varchar(50) NOT NULL DEFAULT '',
`firstname` varchar(100) DEFAULT NULL,
`lastname` varchar(100) DEFAULT NULL,
`middleName` varchar(100) DEFAULT NULL,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`dob` date DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`occupationId` int(11) DEFAULT NULL,
`userStatusId` int(11) DEFAULT NULL,
`userTypeId` int(11) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`userid`),
UNIQUE KEY `username` (`username`),
KEY `userStatusId` (`userStatusId`),
KEY `userTypeId` (`userTypeId`),
KEY `occupationId` (`occupationId`),
KEY `lastname` (`lastname`),
CONSTRAINT `users_ibfk_1` FOREIGN KEY (`userStatusId`) REFERENCES `userStatus` (`userStatusId`),
CONSTRAINT `users_ibfk_2` FOREIGN KEY (`userTypeId`) REFERENCES `userType` (`userTypeId`),
CONSTRAINT `users_ibfk_3` FOREIGN KEY (`occupationId`) REFERENCES `occupation` (`occupationId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I am doing all my work in Sequel Pro
insert into users (userid, firstname, username, dob)
values ('gg', 'greg', 'greg2', '1980-01-01');
i tried it this was as well and get the same error, then i tried it like this
insert into users (userid,firstname,username,dob)
values ('gg','greg','greg2','1980-01-01');
here is the code I ran before my insert
delimiter $$
create trigger usersInsert
before insert on users
for each row begin
set new.created = now();
set new.age = floor(datediff(now(),dob)/365);
end $$
delimiter ;
I was trying to see if my trigger was working so I inserted a new user into the user table to make sure it was working properly
i found where my error was. it was in my trigger
delimiter $$
create trigger usersInsert
before insert on users
for each row begin
set new.created = now();
set new.age = floor(datediff(now(),new.dob)/365);
end $$
delimiter ;
I wasn't using 'new.dob' when setting a value to dob
Thank You for all of your help!

i want to create a mysql trigger to create primary key as varchar autoincrement

CREATE TABLE `user` (
`user_id` varchar(16) NOT NULL,
`person_id` varchar(16) NOT NULL,
`org_id` varchar(16) NOT NULL,
`email` varchar(32) NOT NULL,
`login_id` varchar(10) NOT NULL,
`password` varchar(32) NOT NULL,
`mobile_no` varchar(12) NOT NULL,
`android_id` varchar(16) NOT NULL,
`activation_status` int(2) NOT NULL,
`pin` varchar(6) NOT NULL,
`role_id` varchar(16) NOT NULL,
`imei` varchar(16) NOT NULL,
`booth_id` varchar(16) NOT NULL,
`Assignment_id` varchar(16) NOT NULL,
`created_by` varchar(16) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`updated_by` varchar(16) DEFAULT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
(Borrowing from How to make MySQL table primary key auto increment with some prefix)
Assuming you already have your user table created, you can write a trigger to generate the id for you automatically. You'll need a dummy table to hold id's auto-generated by MySQL, allowing the trigger can easily pull new, unique ID's from.
The Dummy (Sequence) Table:
CREATE TABLE user_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
The Trigger:
DELIMITER $$
CREATE TRIGGER tg_user_insert
BEFORE INSERT ON user
FOR EACH ROW
BEGIN
INSERT INTO user_seq VALUES (NULL);
SET NEW.user_id = LAST_INSERT_ID();
END$$
DELIMITER ;
I used this to handle a case where I had to generate some seed data for an existing schema (e.g. I could not change the schema). Please note I'm using this in a dev environment - no idea how performant or otherwise production-worthy something like this would be. Hopefully a competent dba can provide more insight - but since the question stands, I had a similar issue, and couldn't find an alternative, hopefully this will help someone else...

Mysql statement insert, if inserted, insert another

I have the following statement:
INSERT INTO `Properties`(`Id`, `Url`, `BrokerId`, `LastFound`) VALUES
(#Id,#Url,#BrokerId,#LastFound)
ON DUPLICATE KEY UPDATE LastFoundOn = #LastFoundOn;
INSERT INTO `Events`(`Id`, `Type`, `DateTime`, `PropertyId`) VALUES
(#EventId,#EventType,#Now,#Id);
There is a foreign key constraint between Properties.Id and Events.PropertyId. And the Url is unique.
This works - almost. When a recod is not inserted, but updated because of duplicate key (Url), then the insert into event will fail, because the foreign key simply doesn't exist. Like this:
Eg:
exists: 1 | http://test1.com | 2 | 2013-03-13
to insert: 2 | http://test2.com | 2 | 2013-03-14
When trying to insert, it updates instead, because of the unique url. When afterwards trying to insert the event, a foreign key (2) doesn't exist in the Properties table. How can I make an if then statement to handle this scenario?
Something like (?):
INSERT INTO `Properties`(`Id`, `Url`, `BrokerId`, `LastFound`) VALUES
(#Id,#Url,#BrokerId,#LastFound)
ON DUPLICATE KEY UPDATE LastFoundOn = #LastFoundOn;
IF LastInserted = #Id THEN
INSERT INTO `Events`(`Id`, `Type`, `DateTime`, `PropertyId`) VALUES
(#EventId,#EventType,#Now,#Id);
END IF;
UPDATE:
A trigger might be the solution, but I'm struggeling making it work. What's wrong here?
DELIMITER $$
CREATE TRIGGER Event_Submitted_Trigger AFTER INSERT ON Properties
FOR EACH ROW
BEGIN
INSERT INTO Events VALUES(SELECT(UUID()), 'PropertySubmitted', SELECT(NOW()), new.Id);
END$$
I get the following error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT(NOW()), new.Id); END$$' at line 4
Best regards,
Søren
UPDATE:
Here is my schema:
CREATE TABLE IF NOT EXISTS `Events` (
`Id` char(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`Type` enum('PropertySubmitted','PropertyChanged','PropertyRemoved') NOT NULL,
`DateTime` datetime NOT NULL,
`Attribute` varchar(128) NOT NULL,
`From` varchar(512) NOT NULL,
`To` varchar(512) NOT NULL,
`PropertyId` char(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`Id`),
KEY `IX_FK_PropertyEvent` (`PropertyId`),
KEY `DateTimeIndex` (`DateTime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `Properties`
--
CREATE TABLE IF NOT EXISTS `Properties` (
`Id` char(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`Url` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`Type` varchar(64) NOT NULL,
`ExtractedAddress` varchar(192) NOT NULL,
`ExtractedPostcode` varchar(8) NOT NULL,
`ExtractedCity` varchar(64) NOT NULL,
`StreetName` varchar(128) DEFAULT NULL,
`StreetNumber` varchar(8) DEFAULT NULL,
`Floor` varchar(8) DEFAULT NULL,
`Side` varchar(8) DEFAULT NULL,
`DoorNo` varchar(8) DEFAULT NULL,
`Postcode` int(4) DEFAULT NULL,
`City` varchar(64) DEFAULT NULL,
`Latitude` double DEFAULT NULL,
`Longitude` double DEFAULT NULL,
`ImageUrl` varchar(512) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Price` int(8) NOT NULL,
`Payout` int(8) NOT NULL,
`GrossPrice` int(6) NOT NULL,
`NetPrice` int(6) NOT NULL,
`Area` int(5) NOT NULL,
`GroundArea` int(5) NOT NULL,
`Rooms` int(2) NOT NULL,
`Year` int(4) NOT NULL,
`PriceChange` int(11) NOT NULL,
`FirstFoundOn` datetime NOT NULL,
`SubmittedOn` datetime NOT NULL,
`LastFoundOn` datetime NOT NULL,
`FoundAt` varchar(256) DEFAULT NULL,
`Validated` tinyint(1) NOT NULL,
`BrokerId` char(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`Archived` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`),
UNIQUE KEY `Url` (`Url`),
KEY `IX_FK_PropertyBroker` (`BrokerId`),
KEY `UrlIndex` (`Url`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Triggers `Properties`
--
DROP TRIGGER IF EXISTS `Event_Submitted_Trigger`;
DELIMITER //
CREATE TRIGGER `Event_Submitted_Trigger` AFTER INSERT ON `Properties`
FOR EACH ROW BEGIN
INSERT INTO `Events` VALUES(UUID(), 'PropertySubmitted', NOW(), NEW.Id);
END
//
DELIMITER ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `Events`
--
ALTER TABLE `Events`
ADD CONSTRAINT `Events_ibfk_1` FOREIGN KEY (`PropertyId`) REFERENCES `Properties` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `Properties`
--
ALTER TABLE `Properties`
ADD CONSTRAINT `Properties_ibfk_2` FOREIGN KEY (`BrokerId`) REFERENCES `Brokers` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
Assuming the following structure:
CREATE TABLE Properties (
id INT,
url VARCHAR(100),
lastFound DATETIME,
UNIQUE (url)
) ;
CREATE TABLE Events (
id VARCHAR(36),
type VARCHAR(20),
t DATETIME,
propertyId INT
) ;
Here is a working trigger:
DELIMITER $$
CREATE TRIGGER Event_Submitted_Trigger AFTER INSERT ON Properties
FOR EACH ROW BEGIN
INSERT INTO Events VALUES( UUID(), 'PropertySubmitted', NOW(), new.Id);
END $$
DELIMITER ;
See it in action here. Notice the NOW()+SLEEP(1) hack, only meant to delay execution in order to get a significant result (SLEEP() returns 0 if not interrupted).

Mysql Trigger Loop for query result with many rows

hi i have a database with many tables and foreign keys like this
CREATE TABLE IF NOT EXISTS `articulos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(63) NOT NULL,
`contenido` text NOT NULL,
`normas_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=138 ;
CREATE TABLE IF NOT EXISTS `aspectosambientales` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(63) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=28 ;
CREATE TABLE IF NOT EXISTS `aspectosambientales_articulos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`aspectosambientales_id` int(11) NOT NULL,
`articulos_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_aspaspectosambientales1` (`aspectosambientales_id`),
KEY `fk_aspee` (`articulos_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 UTO_INCREMENT=225 ;
CREATE TABLE IF NOT EXISTS `empresas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`razonsocial` varchar(127) DEFAULT NULL,
`nit` varchar(63) DEFAULT NULL,
`direccion` varchar(127) DEFAULT NULL,
`telefono` varchar(15) DEFAULT NULL,
`web` varchar(63) DEFAULT NULL,
`auth_user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
CREATE TABLE IF NOT EXISTS `articulos_empresas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`empresas_id` int(11) NOT NULL,
`articulo_id` int(11) NOT NULL,
`acciones` text,
`responsable` varchar(255) DEFAULT NULL,
`plazo` date DEFAULT NULL,
`cumplido` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_normas_empresas_empresas1` (`empresas_id`),
KEY `fk_normas_empresas_normas1` (`normas_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
and i need to create a trigger to fill the 'articulos_empresas' after insert in 'empresas' for all rows in 'articulos' that match with 'aspectosambientals' that the new 'empresas' selected.
I get all 'articulos' with this query
SELECT articulos_id FROM aspectosambientales_articulos
WHERE aspectosambientales_id = ID
-- ID is the aspectosambientales_id selected when the 'empresas' row is created
-- maybe something like NEW.aspectosambientales_id
but i dont know how create a loop like ' for loop' in trigger for every result in the query
some like this:
CREATE TRIGGER 'filltableae' AFTER INSERT ON 'empresas'
FOR EACH ROW
BEGIN
DECLARE arrayresult = (SELECT articulos_id FROM aspectosambientales_articulos
WHERE aspectosambientales_id = NEW.aspectosambientales_id)
--- here is when i have to do the loop for all the results
--- for ids in arrayresults
--- insert into articulos_empresas ('',NEW.id, ids, '', '' ,'','')
--- endfor
END
thanks!!!
Based on #Razvan answer i left here the code for the trigger, so maybe can help somebody
DROP TRIGGER IF EXISTS AEINST;
DELIMITER //
CREATE TRIGGER AEINST AFTER INSERT ON procesos_aspectos
FOR EACH ROW
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE ids INT;
DECLARE cur CURSOR FOR SELECT articulos_id FROM aspectosambientales_articulos WHERE aspectosambientales_id = NEW.aspectosambientales_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
ins_loop: LOOP
FETCH cur INTO ids;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO articulos_empresas VALUES (null,ids, NEW.empresas_id,null,null,null,null);
END LOOP;
CLOSE cur;
END; //
DELIMITER ;
thanks again!
As far as I know you can iterate through the result of a SELECT query using cursors.
See here : http://dev.mysql.com/doc/refman/5.0/en/cursors.html