MYSQL: Insert autoincrement value into several columns - mysql

Can you insert an autoincrement value into several columns at once?
Example table `zoo`:
id (int autoincrement primary_key);
parent (int);
data (varchar,10).
INSERT INTO zoo (id, parent, data) VALUES (NULL, id, "tiger");
Or do I have to do a second query?
UPDATE TABLE zoo SET parent=id WHERE parent IS NULL;

You might be able to do this via a before insert trigger:
DELIMITER //
CREATE TRIGGER same_id_trigger
BEFORE INSERT
ON zoo FOR EACH ROW
BEGIN
DECLARE id int DEFAULT 0;
SELECT auto_increment INTO id
FROM information_schema.tables
WHERE table_name = 'zoo' AND table_schema = database();
SET NEW.parent = id;
END; //
DELIMITER ;
Assuming the above trigger works, then it is working by directly querying information schema to find the current auto increment value for the zoo table. Then, the trigger effectively intercepts the insert, and swaps in that auto increment value for the parent column.

Related

How to make unique incrementing counter in MySQL

How to assign unique auto incrementing values to a certain column? Kind of like AUTO_INCREMENT does but it should be NULL at the time of insertion and assigned at some later point.
I have a table that gets regular data inserts and a few workers that process that data and set processed_at datetime field when they're done. Now I want incrementally select new processed rows since the last call. If I naively use where processed_at > #last_update_time I'm afraid there might be a situation where some records are processed at the same second and I miss some rows.
update: Can I just do
begin;
select #max := max(foo) from table1;
update table1 set foo = #max + 1 where id = 'bar' limit 1;
commit;
if foo column is indexed?
You can use a trigger to implement that.
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');
CREATE TRIGGER pk AFTER UPDATE ON your_table_name
BEGIN
UPDATE my_increment
SET value = value + 1
WHERE table_name = 'your_table_name';
UPDATE your_table_name
SET ID2 = (
SELECT value
FROM my_increment
WHERE table_name = 'your_table_name')
WHERE ROWID = new.ROWID;
END;
But bear in mind that this trigger will work on every execution of the Update query.
You can also do it manually:
Create the table to store increment value:
CREATE TABLE my_increment (value INT, table_name TEXT);
INSERT INTO my_increment VALUES (0, 'your_table_name');
Then when you want to update the table, get the last value from this table and insert value+1 to your column needed to be incremented.

Autofill column in MySql based on two columns

I have an sql db with two columns A and B where A is an autoincrement. Is there any way to autofill a column C whenever an entry is inserted using Hibernate. The column C will be the concatenation of values in B and A i.e. B_A?
You could use a BEFORE INSERT TRIGGER (https://www.techonthenet.com/mysql/triggers/before_insert.php) which can change values for your insert.
CREATE TRIGGER addRow BEFORE INSERT ON table
FOR EACH ROW
BEGIN
SET new.C = concat(new.a, '_', new.b);
END
Edit:
You can fetch the auto increment value using:
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='tbl');
SET NEW.field=next_id;
Use below query :
SELECT CONCAT(char_col,'_',CAST(int_col AS CHAR));

How to auto increment in phpmydamin with custom number and character string

How can I set my custom value in auto increment column when insert query fire in phpMyAdmin
I want like when I insert a data in MySQL at that time the auto increment column value add with like something ABC001 and next record will be ABC002
It there any way to setup this functionality
This is my table structure
I want new code for every insert query for red mark field
Yes, you can use a TRIGGER like this:
CREATE DEFINER=`root`#`localhost` TRIGGER `setDrinkk` BEFORE INSERT ON `yourTable`
FOR EACH ROW BEGIN
SET NEW.DrinkCode = CONCAT('ABC-', LPAD(NEW.db_id,4,'0'));
END
You'll have to add 2 more fields to the table..One field(eg:drink_text)containing the text 'ABC' and other field (Eg:drink_no) with autoincrement.
Set default value of drink_text as ABC.
Set autoincrement primary key for drink_no
ALTER TABLE tablename AUTO_INCREMENT=101;
Now in insert query you have to concatenate both the fields to drink_code
//your insert query
INSERT INTO tablename( user_id,club_id) VALUES ('xyz','abc');
//drink_code with custom string
UPDATE tablename SET drink_code = concat( drink_text, drink_no ) ;

Script/workflow insert not exist and auto increment

I create a script/workflow exportation/importation from 2 system.
I have Table1 {id, name, description}
I want to create a script (not a procedure). I could (I didnt succed) adding procedure into my workflow. (create and delete at the end)
id is auto increment
I cant change the table
I can be sure that between the time I start execution of my script and the end, there will not be an insertion of one of my items into the database.
The script insert {name,description} but I want to NOT insert if the element (name or name and description) is there.
BASE QUERY :
INSERT INTO TABLE1 (name,description) VALUES ('itemX','this is item X')
BASE Script :
Use database1;
BEGIN;
SELECT * FROM TABLE1 ;
SELECT * FROM TABLE3 ;
INSERT INTO TABLE1 (name,description) VALUES ('itemX','this is item X');
set #idTable1 = LAST_INSERT_ID();
INSERT INTO TABLE3 (idTable1,idTable2) VALUES (#idTable1,1);
INSERT INTO TABLE3 (idTable1,idTable2) VALUES (#idTable1,2);
SELECT * FROM TABLE1 ;
SELECT * FROM TABLE3 ;
ROLLBACK;
I want to protect the multiple insertion on TABLE1. But without changing the table.
Maybe I did it wrong
I tried IF but not working outside procedure.
I tried IGNORE (valid only if id is the same, but never the same, its
auto increment)
I tried WHEN
I tried ON DUPLICATE KEY
Because of #idTable1, I will need change the " set #idTable1 = LAST_INSERT_ID();" if I doesnt have if else. But if my item is the only one with the same "name", I can get this instead of last_insert_id.
I opted for creating procedure before my "BEGIN" and removed them at the end of the script.
Just create the table with name as primary key, then be sure that you take care of the key capitalization (uppercase or lowercase) to avoid duplicates.
CREATE TABLE TABLE1(
id INT AUTO_INCREMENT,
name CHAR(30),
description CHAR(100),
PRIMARY KEY (name)
)
create unique constraint on name field if possible.
Otherwise, create trigger before insert in order to ignore duplicate insertion.
Trigger for checking duplicate on two fields a and b:
delimiter //
drop trigger if exists aborting_trigger //
create trigger aborting_trigger before insert on t
for each row
begin
set #found := false;
select true into #found from t where a=new.a and b=new.b;
if #found then
signal sqlstate '45000' set message_text = 'duplicate insert';
end if;
end //
delimiter ;
The trigger here provides feature similar to unique constraint. After creation you should use INSERT IGNORE or INSERT ...ON DUPLICATE KEY UPDATE

Using MyISAM table to increment multiple values on mysql

I have this table: cd_biblio which has a list of books.
When I insert a new book from my php page, I want to increment a field ('Ingresso') based on the value 'Class' I inserted.
For example:
I insert a new book with class 'A', his 'Ingresso' value will be the current max of 'Ingresso' for the class 'A' + 1.
How can I do this using MyISAM?
use prodedures or triggers f.e:
delimiter ~
CREATE PROCEDURE AddBook(...)
BEGIN
DECLARE gIngresso INT DEFAULT 0;
SELECT Max(Ingresso) INTO gIngresso FROM Table;
INSERT INTO Table VALUE(... , gIngresso)
END~
delimiter ;