Question

I have a table in mysql. It has a few records from before. Its fields are a, b and c. Sometimes I insert a record in this table like for example this with different values:

$query = "INSERT INTO table(a, b, c) VALUES('1', '0', '2')";

Values are characters. Seems last record in the table is 5, 6, 4. I mean a=5, b=6 and c=4 and I want to insert a new record. My values are 1 and 0 and 2 but I want you to help me for this method: When b == 0, I don't want to save it and instead, I want to save the last field in the table. For example I am inserting 1, 0, 2 and it just insert a=1 and c=2 but it inserts the last field in table instead this 0 that it is 6.

something like this:

if(false)
{
    $query = "INSERT INTO table(a, b, c) VALUES('1', The Last Value In Table, '2')";
}

I would rather not to read last record of table and use its value because it can decrease the speed for me and speed is very important. Its better to use a mysql command that does it automatically.

Was it helpful?

Solution

As you need the data of the last inserted record you must get it from somewhere. The first thing that comes to mind is: read the table and look for the last inserted record, which is something you don't want, maybe because the table is too large to access the data quickly.

So you need a lookup table, containing only the last inserted values (i.e. one record):

create table last_insert_mytable(a varchar, b varchar, c varchar);

Which you fill with a trigger:

create trigger trg_mytable_last_insert after insert on mytable
  for each row begin
    delete from last_insert_mytable;
    insert into last_insert_mytable (a, b, c) values (new.a, new.b, new.c);
  end;

So your insert statement looks like this:

insert into mytable(a, b, c) 
values ('1', (select b from last_insert_mytable), '2');

or (provided there is already a record in last_insert_mytable):

insert into mytable(a, b, c) 
select '1', b, '2' from last_insert_mytable;

Keep in mind that every insert gets a bit slowed down due to the trigger. As there is only one record to deal with, it can be faster than to have to look up the last inserted record in mytable. This depends on the size of mytable. This happens for every insert into mytable. If it is rather seldom to have to look up the latest record, it may be better to have a slow lookup every now and then, than to have a slightly slower insert every time. Well, just try it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top