Mysql: update current value if previous row are same with current row - mysql

How do i update current row value if my previous row are same with current row.
example:
the curent row is 68, previous row is also 68.. i would i like to update current row become 68-20 which is 48.
same for 98-20 = 78.
so that the corrected data will look like:
i have more than 1000 record like this, which cant update the record one by one manually.
update table1 set DIH_QTY_BALANCE=DIH_QTY_BALANCE-DIH_REORDER_QTY
WHERE how to put the previous row same as current on where clause?
Here is the Schema + data:
http://pastebin.com/T1tYDT6Y
too large for sqlfiddle.
any help would be great.

As far as I remember, MySQL has problems to select from the same table in an update statement. And this is what you would have to do, because in order to update a record or not, you'd have to select its previous record from the same table.
So create a temporary table, give it row numbers, then select from it with a self join, to compare each record with its previous record.
create temporary table temp
(
rownum int,
dihistoryid int,
dih_qty_balance int
) engine = memory;
set #num = 0;
insert into temp
select
#num := #num + 1 as rownum,
dihistoryid,
dih_qty_balance
from mytable
order by dihistoryid;
update mytable
set dih_qty_balance = dih_qty_balance - dih_reorder_qty
where dihistoryid in
(
select current.dihistoryid
from temp current
join temp previous on previous.rownum = current.rownum - 1
where previous.dih_qty_balance = current.dih_qty_balance
);
drop temporary table temp;

May be something like this
SELECT DIH_QTY_BALANCE,
(SELECT DIH_QTY_BALANCE FROM example e2
WHERE e2.DIHISTORYID < e1.DIHISTORYID
ORDER BY DIHISTORYID DESC LIMIT 1) as previous_value,
(SELECT value FROM example e3
WHERE e3.DIHISTORYID > e1.DIHISTORYID
ORDER BY DIHISTORYID ASC LIMIT 1) as next_value
FROM example e1

Related

Updating all rows at once in mysql table with subquery

I have this table seller whose columns are
id mobile1
1 787811
I have another table with same columns ,I just want to update the mobile1 field from this table with the values from other table say "copy".
I have written this query
UPDATE seller
SET mobile1 = (
SELECT SUBSTRING_INDEX(mobile1, '.', 1)
FROM copy)
WHERE 1;
I am getting this obvious error when I run it.
Sub-query returns more than 1 row ,
Any way to do this??
You need condition which will be using to select only one row or you should use LIMIT:
UPDATE seller
SET mobile1 = (
SELECT SUBSTRING_INDEX(mobile1, '.', 1)
FROM copy
LIMIT 1)
WHERE id = 1;
You can constrain the number of rows returned to just one using MySQL limit.
UPDATE seller SET mobile1=(SELECT SUBSTRING_INDEX(mobile1,'.',1)
FROM copy LIMIT 1)
WHERE id=1;
If anyone who is looking for the possible answer here is what I did,I created a procedure with while loop.
DELIMITER $$
CREATE PROCEDURE update_mobile(IN counting BIGINT);
BEGIN
declare x INT default 0;
SET x = 1;
WHILE x <= counting DO
UPDATE copy SET mobile1=(SELECT SUBSTRING_INDEX(mobile1, '.', 1) as mobi FROM seller WHERE id=x LIMIT 1) WHERE id=x;
SET x=x + 1;
END WHILE;
END
AND finally I calculated the number of rows by count(id) and passed this number to my procedure
SET #var =count;
CALL update_mobile(#var);
AND it worked like a Charm...
If you want to copy all data, you can do this :
INSERT INTO `seller` (`mobile1`) SELECT SUBSTRING_INDEX(mobile1,'.',1) FROM copy

SQL - update table with sequential numbering

i have a table in my MySQL database which i have added a new column to.
I would like to update this column on every row with a number starting at 20000 going up +1 each time.
i have tried this solution:
UPDATE table1 set new_col = new_col + 1;
but it just updates all rows with the same number
The easy way:
UPDATE table1 t, (SELECT #nr:= 20000-1) tmp
SET t.new_col = (#nr:=#nr+1) ;
I have used this query to solve this:
SET #rank:=20000;
update customer
set accountnumber_new=#rank:=#rank+1

Limiting table rows

How can I store only 10 rows in a MySQL table? The older rows should be deleted when a new row is added but only once the table has 10 rows.
Please help me
You could achieve this with an after insert trigger, delete the row where it is min date. e.g. DELETE FROM myTable WHERE myTimestamp = (SELECT MIN(myTimestamp) FROM myTable) but that could in theory delete multiple rows, depending on the granularity of your updates.
You could have an incrementing sequence, and always just delete the min of that sequence.
The question is why you'd want to do this though? It's a slightly unusual requirement.
A basic example (not validated/executed, I don't have mySQL on this particular machine) would look something like.
CREATE TRIGGER CycleOldPasswords AFTER INSERT ON UserPasswords FOR EACH ROW
set #mycount = SELECT COUNT(*) FROM UserPasswords up where up.UserId = NEW.UserId;
if myCount >= 10 THEN
DELETE FROM UserPasswords up where up.Timestamp = (SELECT min(upa Timestamp) FROM UserPasswords upa WHERE NEW.UserId = upa.UserId) AND NEW.UserId = up.UserId;
END
END;
You can retrieve the last inserted id when your first row is inserted, and store it in a variable. When 10 rows are inserted, delete the row having id < id of the first inserted record. Please try it.
first of all insert all values using your insert query
and then run this query
delete from table_name where (cond) order by id desc limit 10
must specify an id or time in one column

Insert sequential number in MySQL

I added an empty column to a table and now I want to insert sequential numbers to its rows. Is it possible to do it using SQL?
Run the following queries to have incremented value in yourField column:
SELECT #i:=0;
UPDATE yourTable SET yourField = #i:=#i+1;
As I said in comments you can update every row with its row number,
Here is a link to how to calculate rownum in MySQL.
To rephrase:
update player,
(select #rownum:=#rownum+1 ‘rank’, p.*
from player p,
(SELECT #rownum:=0) r
order by score desc) player1
set thatColumn= rank
where player.id = player1.id
try this auto increment
if you wanted to have incremental number in your table for each insert that you do
create table WithAutoInc(somID int AUTO_INCREMENT,somName_ char(100) ,primary key(somID ));
now to insert you can do this
insert into WithAutoInc (somName_) values ('presley');
the result is

How to delete every record after the nth row in mysql?

In mysql I can query select * ... LIMIT 10, 30 where 10 represents the number of records to skip.
Does anyone know how I can do the same thing in delete statements where every record after the first 10 records get deleted?
Considering there is no rowId in MySQL (like in Oracle), I would suggest the following:
alter table mytable add id int unique auto_increment not null;
This will automatically number your rows in the order of a select statement without conditions or order-by.
select * from mytable;
Then, after checking the order is consistent with your needs (and maybe a dump of the table)
delete from mytable where id > 10;
Finally, you may want to remove that field
alter table mytable drop id;
The following will NOT work:
DELETE
FROM table_name
WHERE id IN
( SELECT id
FROM table_name
ORDER BY --- whatever
LIMIT 10, 30
)
But this will:
DELETE
FROM table_name
WHERE id IN
( SELECT id
FROM
( SELECT id
FROM table_name
ORDER BY --- whatever
LIMIT 10, 30
) AS tmp
)
And this too:
DELETE table_name
FROM table_name
JOIN
( SELECT id
FROM table_name
ORDER BY --- whatever
LIMIT 10, 30
) AS tmp
ON tmp.id = table_name.id
When deleting a lot of rows, this is an efficient trick:
CREATE TABLE new LIKE real; -- empty table with same schema
INSERT INTO new SELECT * FROM real ... LIMIT 10; -- copy the rows to _keep_
RENAME TABLE real TO old, new TO real; -- rearrange
DROP TABLE old; -- clean up.