Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert substring content into new column at data insertion

Tags:

mysql

I have table table with three columns as follows

CREATE TABLE `auto_bulk` (
  `bulk_id` int(5) NOT NULL auto_increment,
  `heading` varchar(25) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY  (`bulk_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

I need to add some bulk records directly to mysql database.

INSERT INTO auto_bulk(heading,content)VALUES('xxx','xxx');

But my problem is I am giving only the content,heading should be the first 5 letters of content.Like,

INSERT INTO auto_bulk(heading,content)VALUES('Hello','Helloworld123');

I know how to do with php with substr but i would like to know is there any way to do it directly in mysql I have tried this but no luck

INSERT INTO auto_bulk(heading,content)VALUES(SUBSTRING(content,1,5),'Helloworld123');

Thanks

like image 682
vinu Avatar asked Dec 05 '25 02:12

vinu


2 Answers

Try:

INSERT INTO auto_bulk(content,heading)
SELECT @var := 'Helloworld123', SUBSTRING(@var,1,5);
like image 160
DWright Avatar answered Dec 07 '25 17:12

DWright


Create a BEFORE INSERT trigger like this:

DELIMITER $$

CREATE TRIGGER auto_bulk_trigger1
    BEFORE INSERT
    ON auto_bulk
    FOR EACH ROW
BEGIN
    SET NEW.heading = LEFT(NEW.content, 5);
END
$$

DELIMITER ;

Then insert just content:

INSERT INTO auto_bulk(content) VALUES('Helloworld123');
like image 41
peterm Avatar answered Dec 07 '25 17:12

peterm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!