I have a table with the following structure:
id | number | text
----------------------
1 | 1 | test
in which, id is my primary key with auto increment value. I want to make number as auto increment value too. Is it possible to have more than one auto increment column in one table?
It is not possible.There can be only one auto-increment column and it must be defined as a key in MySQL.
But You can do it by using trigger for detail go this link CREATE TRIGGER
create trigger nameTrigger before insert on tables
for each row
begin
DECLARE newNumber unsigned default 0;
SELECT Max(number)+1 INTO newNumber FROM myTable WHERE id = new.id;
UPDATE myTable SET number = newNumber WHERE id = new.id;
end
Related
My first aim is to generate customer reference code automaticaly everytime when I insert a new customer
so when it shown in my nodejs it should be : "MS2200001"
So my idea is set id from customer table (mysql) with auto increment and zerofill (int)
length = 5
So I can get id 00001
and insert to another column named as "customer reference"
with
("MS" + (2022)+ "00001")
And I am trying to reset the counter to 00001 again if become 2023,2024,2025 etc.
How can I archive this in phpmyadmin or I should chnage my idea?
Use trigger-generating technique and additional MyISAM table with secondary AUTO_INCREMENT column in PRIMARY KEY.
An example:
-- base table for complete identifier generation
CREATE TABLE base_for_complete_id (
`year` YEAR,
id INT AUTO_INCREMENT,
PRIMARY KEY (`year`, id)
) ENGINE = MyISAM;
-- create trigger which will generate complete identifier
CREATE TRIGGER generate_complete_id
BEFORE INSERT ON maintable
FOR EACH ROW
BEGIN
DECLARE tmp INT;
-- insert row into base table
INSERT INTO base_for_complete_id (`year`) VALUES (YEAR(NEW.created_at));
-- store id generated for current year
SET tmp = LAST_INSERT_ID();
-- save generated complete identifier into main table
SET NEW.complete_id = CONCAT('prefix_', YEAR(NEW.created_at), '_', tmp);
-- clear excess rows from base table
DELETE FROM base_for_complete_id WHERE `year` = YEAR(NEW.created_at) AND id < tmp;
END
DEMO fiddle
If you need to format id part of generated value with leading zeros then use LPAD() function, for example SET tmp = LPAD(LAST_INSERT_ID(), 5, 0);.
Caution! If the value for generated number exceeds 99999 then it will be truncated, and only 5 leading digits will be stored.
i have multiple user like admin and vendor etc. Now i want to add prefix in id field value while inserting data like if use is admin then value of id field is "A_1" or user is vendor then the value should be "V_1", while id field is autoincremented.Anyone has idea about this please comment.Thank you.
you can do it with sequence and trigger
here is a working example
create table tbl_usertypes(
usertypes_id varchar2(50),
name varchar2(50),
usertype varchar2(50),
CONSTRAINT pk_usertypes_id PRIMARY KEY(usertypes_id)
);
desc tbl_usertypes;
CREATE SEQUENCE sq_usertypes_id START WITH 1;
create or replace trigger add_random_id
BEFORE INSERT ON tbl_usertypes
FOR EACH ROW
BEGIN
IF :NEW.usertype = 'admin' THEN
SELECT 'A_' || sq_usertypes_id.NEXTVAL INTO :NEW.usertypes_id FROM dual;
ELSE
SELECT 'B_' || sq_usertypes_id.NEXTVAL INTO :NEW.usertypes_id FROM dual;
END IF;
END;
INSERT INTO tbl_usertypes values(null,'hoax', 'admin');
INSERT INTO tbl_usertypes values(null,'hoax', 'user');
select * from tbl_usertypes;
and the result
For auto incrementing an ID you can read something about auto increment on sql:
Some example of Identity used to auto increment an ID used as a Primary Key:
CREATE TABLE Test_AutoIncrement(
ID int AUTO_INCREMENT,
Name varchar(50) NULL,
Something varchar(100) NOT NULL,
PRIMARY KEY(ID));
In this case you didn't have to specify the ID filed during any INSERT statement, SQL will manage that.
For example we have some records of this tabel like:
ID | Name | Something |
1 "Simo" "Foo"
2 "Fred" "Bar"
Now, we simulate an Insert statement on our Test_AutoIncrement table:
INSERT INTO Test_AutoIncrement
VALUES(
NULL,
"FooBar()"
);
Now our Table will be as follow:
ID | Name | Something |
1 "Simo" "Foo"
2 "Fred" "Bar"
3 NULL "FooBar()"
Remarks:
In the above case we start with ID=1 and it will increment it by 1 on every new record.
You can specify ID=0 in the insert if you want to start counting from zero but NO_AUTO_VALUE_ON_ZERO must be disabled from MySQL.
I have fields in the table which are id, name, employee_id. The id column is the primary key with auto increment.In this table,
I need one column which called employee_id start from A5001, A5002, A5003...and soon.
I tried below code.
Table
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
employee_id VARCHAR(30) NOT NULL DEFAULT '0'
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.employee_id = CONCAT('A', LPAD(LAST_INSERT_ID(), 4, '500'));
END$$
DELIMITER ;
Then just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('ABC'),('ZXD'),('POI');
Finally, I got my output.
1|ABC | A5001
2|ZXD | A5002
3|POI | A5003
and so on
Now My issue is, I inserted 1000 rows in the table so my id is 1000 but there is some issue with my employee_id because after getting the A5999 it starts from A1000 which is totally wrong I need continuously like A6000, A6001, A6002.. and so on
I think there is some issue with my trigger.
Would you help me out in this?
You can use mathematical addition instead of string padding:
SET NEW.employee_id = CONCAT('V', 5000 + LAST_INSERT_ID());
Explanation:
I'm just adding 5000 to last insert ID. Think of it:
1st ID would be 5000 + 1 = 5001
999th ID would be 5000 + 999 = 5999
1000th ID would be 5000 + 1000 = 6000
It will never throw an ID shorter than 4 digits, so there is no need of LPAD.
Warning: You have to think what do you want after 4999th insert. It will cause an ID of 5 digits (5000 + 5000 = 10000). If you don't have a problem with 5 digits, leave it this way.
I have an auto increment column ID, and for some situation I wanted the other column to be equal to the primary key + 1 value
ID | other
1 | 2
2 | 3
3 | 4
4 | 123 (some situation, it is not always plus 1)
How can I achieve this?
Here's what I have tried
INSERT INTO table (`ID`,`other`) VALUES ('',(SELECT MAX(ID)+1 FROM table))
But that returns an error
You can't specify target table 'table' for update in FROM clause
Try Below query:
ALTER TABLE dbo.table ADD
Column AS ([ID]+1)
GO
It will definitely work
Using a normal AUTO_INCREMENT column as id, I cannot think of a way to do this in MySQL. Triggers, which otherwise would have been an option, don't work well with AUTO_INCREMENT columns.
The only way I see is to do two commands for an INSERT;
INSERT INTO bop (value) VALUES ('These values should be 1 and 2');
UPDATE bop SET other = id+1 WHERE id = LAST_INSERT_ID();
An SQLfiddle to test with.
The closest I'm getting to what you're looking for is to generate sequences separately from AUTO_INCREMENT using a function, and use that instead to generate the table id;
DELIMITER //
CREATE TABLE bop (
id INT UNIQUE,
other INT,
value VARCHAR(64)
)//
CREATE TABLE bop_seq ( seq INT ) // -- Sequence table
INSERT INTO bop_seq VALUES (1) // -- Start value
CREATE FUNCTION bop_nextval() RETURNS int
BEGIN
SET #tmp = (SELECT seq FROM bop_seq FOR UPDATE);
UPDATE bop_seq SET seq = seq + 1;
RETURN #tmp;
END//
CREATE TRIGGER bop_auto BEFORE INSERT ON bop
FOR EACH ROW
SET NEW.id = bop_nextval(), NEW.other=NEW.id + 1;
//
That'd let you do inserts and have it autonumber like you want. The FOR UPDATE should keep the sequence transaction safe, but I've not load tested so you may want to do that.
Another SQLfiddle.
I solved this by updating 2 times the DB..
I wanted to do +1 from 19 till ..
UPDATE `table` SET `id`=`id`+101 WHERE id <= 19
UPDATE `table` SET `id`=`id`-100 WHERE id <= 119 AND id >= 101
Say I have a MySQL table with an auto incrementing id field, then I insert 3 rows. Then, I delete the second row. Now the id's of the table go 1,3. Can I get MySQL to correct that and make it 1,2 without having to write a program to do so?
MySQL won't let you change the indexing of an Auto-Index column once it's created. What I do is delete the Auto-Index column and then add a new one with the same name, mysql will index the newly generated column with no gaps. Only do this on tables where the Auto-Index is not relevant to the rest of the data but merely used as a reference for updates and deletes.
For example I recently did just that for a table containing proverbs where the Auto-Index column was only used when I updated or deleted a proverb but I needed the Auto-Index to be sequential as the proverbs are pulled out via a random number between 1 and the count of the proverbs, having gaps in the sequence could have led to the random number pointing to a non-existant index.
HTH
Quoting from The Access Ten Commandments (and it can be extensible to other RDBMS: "Thou shalt not use Autonumber (or Auto Incremental) if the field is meant to have meaning for thy users".
The only alternative I can think of (using only MySQL) is to:
Create a trigger that adds the row number to a column (not the primary key)
Create a procedure to delete rows and update the row number (I couldn't make this work with triggers, sorry)
Example:
create table tbl_dummy(
id int unsigned not null auto_increment primary key,
row_number int unsigned not null default 0,
some_value varchar(100)
);
delimiter $$
-- This trigger will add the correct row number for each record inserted
-- to the table, regardless of the value of the primary key
create trigger add_row_number before insert on tbl_dummy
for each row
begin
declare n int unsigned default 0;
set n = (select count(*) from tbl_dummy);
set NEW.row_number = n+1;
end $$
-- This procedure will update the row numbers for the records stored
-- after the id of the soon-to-be-deleted record, and then deletes it.
create procedure delete_row_from_dummy(row_id int unsigned)
begin
if (select exists (select * from tbl_dummy where id = row_id)) then
update tbl_dummy set row_number = row_number - 1 where id > row_id;
delete from tbl_dummy where id = row_id;
end if;
end $$
delimiter ;
Notice that you'll be forced to delete the records one by one, and you'll be forced to get the correct primary key value of the record you want to delete.
Hope this helps