Update the ID(auto increment column) of a row - mysql

I am having one table in which ID column is 'Auto Increment' set.
CREATE TABLE tablename(
ID int(11) unsigned int not null auto_increment,
Name varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now I have one row in table whose ID filed is 100. But I want to move this row to the next auto incremental value. Let's say if the last row entered in the table is 1005 so row of ID=100 will move to 1006.
Simple way to solve this problem is
Select -> Insert -> Delete
But I want to know if I can do something like below:
UPDATE table SET ID=last_insert_id()+1 where ID=100

Related

adding a kind of auto increment column to a mysql table

I want to add a column to a mysql table where its cells will get values like:
newColumn
-----------
log-00001
log-00002
log-00003
....
the values log-0000x will automatically be created by mysql. This is like an "auto incremented" column but with the 'log-' prefix. Is this possible?
Thx
MySQL doesn't auto-increment anything other than integers. You can't auto-increment a string.
You can't use a trigger to populate a string based on the auto-increment value. The reason is that the auto-increment value isn't generated yet at the time "before" triggers execute, and it's too late to change columns in "after" triggers.
See also my answer to https://stackoverflow.com/a/26899091/20860
You can't use a virtual column, probably for the same reason.
mysql> create table t (id int(5) zerofill auto_increment primary key,
virtcolumn char(8) as (concat('log-', id)));
ERROR 3109 (HY000): Generated column 'virtcolumn' cannot refer to auto-increment column.
You'll have to let the integer auto-increment, and then subsequently use UPDATE to populate your "log-nnnnnn" string after the insert is done.
CREATE TABLE `t` (
`id` int(5) unsigned zerofill NOT NULL AUTO_INCREMENT,
`log` char(9) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `t` () VALUES ();
UPDATE `t` SET `log` = CONCAT('log-', `id`) WHERE `id` = LAST_INSERT_ID();
SELECT * FROM `t`;
+-------+-----------+
| id | log |
+-------+-----------+
| 00001 | log-00001 |
+-------+-----------+

How to reset autoincrement value in mysql?

My company has different type of invoices.
Example:
H00001/2013
.
.
.
H99999/2013
and
T00001/2013
.
.
.
T99999/2013
The problem is, the numbering is increasing for new year.
How can I make auto increment value reset for each new year?
This is my current code:
CREATE TABLE `invoices` (
`invoicenumber` mediumint unsigned NOT NULL auto_increment,
`invoicetype` enum('A','B') NOT NULL,
`date` date NOT NULL,
`client` varchar(100) NOT NULL,
PRIMARY KEY (invoicetype,invoicenumber)
) COMMENT='' ENGINE='MyISAM';
Hey if you are using any client application for database like MysqlWorkBench or MYSQL Query Browser
then you can do below steps to set AutoIncrement no -
Right click on Table and go to Alter Table
Select Options tab
Under that you can find Auto Increment label there you can reset the number.
You can reset auto increment value by using the ALTER TABLE statement. The syntax of the ALTER TABLE statement to reset auto increment value is as follows:
ALTER TABLE table_name AUTO_INCREMENT = VALUE;
EDITED:
If you don't want to run this query every year then you have other two option to do such thing as I am aware of this two.
Create cron job/windows scheduled job
As you are using MySql then there is Event Scheduler (Keep in mind this is added in MySql 5.1.6 not in previous versions of MySql)
In your DB table, you can reset the counter with the following code:
ALTER TABLE tablename AUTO_INCREMENT = 1
Perhaps you already found a solution and the answer I'm giving may not be useful, since it's been seven months. Returning to the topic, I noticed that you have a composed primary key with two columns (invoicetype,invoicenumber). So there can be no duplicates of pairs invoicetype,invoicenumber . If you reset the auto_increment every year there might be possible to have duplicate pairs like 'A',1 for two rows, one invoice from year 2013 and the other from year 2014. So you can eliminate that primary key to prevent the violation of the primary key constraint. You can instead define a primary key (any decent table has one) with an auto_incremented column to make every row unique. Then you can define an auto incrementation mechanism for the invoicenumber column (I will shall return to this issue). First I would define the invoice table like this:
CREATE TABLE `invoices` (
`id` int unsigned NOT NULL auto_increment,
`invoicenumber` mediumint unsigned NOT NULL,
`invoicetype` enum('A','B') NOT NULL,
`invoicedate` date NOT NULL, -- not recomended to use reserved words for column names like date
`client` varchar(100) NOT NULL,
PRIMARY KEY (id)
) COMMENT='' ENGINE='MyISAM';
Then I would define another table list_id :
CREATE TABLE `list_id` (
`id` int unsigned NOT NULL auto_increment,
`id_inc` int unsigned NOT NULL, -- number of invoice
`the_year` date NOT NULL, -- year corresponding to the number of invoice
PRIMARY KEY (id)
) COMMENT='' ENGINE='MyISAM';
The above table can be used to set the value of invoicenumber for the current row inserted in invoice table (1 if it is the first invoice of the year of invoicedate, the maximum value of id_inc (coresponding to the year of invoicedate) plus one, otherwise). The rows are completed using a trigger of type before insert for the invoice table. So, before I insert a new invoice, I have to determine the value of invoicenumber. It will be 1, if there are no records in table list_id with column the_year having the value equal to the year of the new invoice. In this case I can insert in table list_id a new record with the values (1,2014) (id_inc,year). It will be the maximum value of id_inc plus 1, if there are record(s) in table list_id with column the_year having the value equal to the year of the new invoice. In this case I can insert in table list_id a new record with the values (7,2014) (id_inc,year). The trigger looks like this:
CREATE TRIGGER `increment_or_reset_new_year`
BEFORE INSERT ON `invoices`
FOR EACH ROW
thisTrigger : begin
declare new_id_year int(11);
declare nr_invoices_year int(11);
declare new_invoice_begin int(11);
declare current_year_row int(11);
set current_year_row = year(new.invoice_date);
set nr_invoices_year = get_nr_invoices_year(current_year_row);
if(get_nr_invoices_year(current_year_row) < 1) then
set new.invoicenumber = 1;
insert into list_id(id_inc,the_year) values (1,current_year_row);
leave thisTrigger;
end if;
if(get_nr_invoices_year(current_year_row) >= 1) then
set new.invoicenumber = get_max_id(year(new.invoice_date)) + 1;
set new_id_year = get_max_id(year(new.invoice_date)) + 1;
insert into list_id(id_inc,the_year) values(new_id_year,year(new.invoice_date));
end if;
end;
There are 2 functions in the trigger. The first one determines the number of rows from the list_id table having the_year equal with the current invoice year (given as parameter):
create function get_nr_invoices_year(invoice_year int) returns int
begin
declare nr_invoices_year int(11);
select count(*) into nr_invoices_year from lista_id where the_year = invoice_year;
return nr_invoices_year;
end;
The second one determines the maximum value of id_inc from table list_id which has the coresponding value of the_year equal with the year of current invoice (given as parameter):
create function get_max_id(year_invoice int) returns int
begin
declare max_id_year int(11);
select max(id_inc) into max_id_year from invoices.lista_id where the_year =year_invoice;
return max_id_year;
end;
So I can have one trigger, two functions and one table which controls the incrementation of invoicenumber.
Hope this helps! It worked for me!

INSERT changes auto_increment, but UPDATE not changes auto_increment?

We have a table:
id int(11) auto_increment
name varchar(255)
auto_increment equals 1.
Insert row:
INSERT INTO `projects` ( `id` , `name`) VALUES ('350', 'project one');
Now auto_increment equals 351.
Update row:
UPDATE `projects` SET `id` = '351' WHERE `id` = 350 LIMIT 1 ;
auto_increment still equals 351. And we get error if try to insert a row:
#1062 - Duplicate entry '351' for key 1
How we can see INSERT changes auto_increment and UPDATE not changes auto_increment.
My goal is to update row and set id greater then auto_increment.
How to do it?
First of all why are you trying to set the auto increment value? Just let it do its job (clue - it is automatic).
So the best solution is when you insert a row let the auto increment chose the appropriate value for you and let that value be an invariant for that rows life time.
Otherwise just remove the auto_increment bit from the table definition and implement an appropriate system yourself.

How to copy a field from a table paste into another table with same properties

I am searching this for hours.
I just want to copy some fields from one table into an another table. In the destination table the fields i want to copy doesn't exsist.
It's like, copy and paste.
Ex. I have to tables
Table A Like
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`active` int(11) DEFAULT '0'
Table B like
`date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`alias` varchar(255) DEFAULT NULL,
`voters` int(11) DEFAULT NULL,
`level` int(11) NOT NULL DEFAULT '0',
`content` text
Ex. I want to copy 'content , level, voters' from Table B to Table A with the same structure and data.
I have in my mind like this, But HOW?
Alter Table A Add content (same SCHEMA as TABLE B.content)
Alter Table A Add level (same SCHEMA as TABLE B.level)
Alter Table A Add level (voters SCHEMA as TABLE B.voters)
INSERT INTO A (col1 , col2 , col3)
SELECT colB1, colB2,colB3
FROM B
they must be that same datatype and size
UPDATE
if table A does not contain data you can create it like this
CREATE TABLE A LIKE B;
Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table:
then make the insert statement above
if you want to keep the data in table A and add some columns from table B you can merge these two table inside new Table X then you delete table A and rename X
CREATE TABLE X
SELECT * from emp;
Note: if table A contains many record this will take too much time and is not a good solution
but your select statement will contains join , if there is a relationship between A and B tell me to write a more specific solution

Why is MySQL auto_increment skipping numbers

We are running an import of an existing product table into a new table of our own. The import script we've written runs perfectly and inserts the right amount of rows (6000 or so). However, after the import the next auto incremented primary key/id is 1500 entries (or so) above the number of rows in the table.
We can't understand why MySQL is doing this and we'd like it to stop. I've done the usual searches online looking for help but I am drawing a blank - any ideas?
Let's take this simple table for example:
CREATE TABLE `products` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(64) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM;
And import file that look like:
"id","name"
1,"product 1"
2,"product 2"
5,"product 3"
102,"product 4"
Then you are importing data to both columns, so auto incrementing mechanism does not work.
After importing all rows, autoincrement value for table is set to MAX(id)+1 [103 in this case] to ensure next autoincremented id is unique. If it was equal to number of rows inserted, then next autincrement value would be 5 and would colide with row #3.
If you want to have clean start and last id equal to number of rows you have to either get rid of "id" column from .csv file, or create table without AUTO_INCREMENT for id, import data and run this simple sql:
SET #i=0;
UPDATE `products` SET id=#i:=#i+1 ORDER BY id;
ALTER TABLE `products` CHANGE COLUMN `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT FIRST;
First query sets auxiliary variable, that will be incremented before updating the record.
Second one updates record to have id equal to row number.
Third will change id column to be autoincremented and set proper value for next autoindex.
But before changing any primary keys ensure that they are not used in any other tables as foreign keys!
If you perform this command:
show create table Foo
Then you will see what the AUTO_INCREMENT= is set too.
My guess is that it is not set to start with 0.
You should then create your new table to have the AUTO_INCREMENT set to 0 (or 1, I cannot remember from the top of my head). This should do the trick.