Limiting table rows - mysql

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

Related

MySql - Add new row for every userId in the table

Below is the table i am trying to write a query for to add new rows for every user.
My question is how do i add a new row for every user? Which means for userId 2 I add AccId 4 and similarly for 7 and 8. Since there is no concept of for loop in sql, do i make use of while? If so, how to loop through the userIds since the IDs are not in equal increments?
something like this maybe:
Insert Into mytable (UserID, AccID)
Select UserID, max(accId)+1
From MyTable
Group By UserID
You can re-run it every time, you will create the next value.
Untested on a MySql server:
INSERT INTO MyTable ( ID, AccId )
SELECT MyValues.ID, MyValues.Espr1
FROM (SELECT MyTable.ID, Max([AccId]+1) AS Espr1
FROM MyTable
GROUP BY MyTable.ID) AS MyValues;
Basically we prefetch Id a AccId grouping the values of Id and grabbing the Max of AccId.
Then we add these rows to the main table. Repeating the query we will add the value 5 (AccId) and so on, always adding 1

INSERT new history rows based on results from UPDATE query

I'd like to
UPDATE table SET column = 1 where column = 0;
INSERT (rows i just updated) INTO history_table;
Can I somehow store the ids from a select query, and then use those to UPDATE and subsequently INSERT rows matching those ids into the history table?
INSERT INTO history_table(id)
(SELECT id from table WHERE column = 0);
UPDATE table SET column = 1 where column = 0;
This way you are only getting the ID's that will be updated for the history_table and then you can update them to the correct values.
(I can't comment yet) Is there a specific reason to do it one query?
If not then you might use temporary table to store ids and fetch them for your update and insert using subquery.

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

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

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

Cleaning old data after inserting the new data into table

First we start with empty table
rows = 0
Second we insert random rows let say 3400
rows = 3400
For the third time i count how many rows are in the table, then insert the new rows and after that delete rows <= from the count.
This logic only work for the first time. If that repeat the count will always be 3400 but the id will increase so it will not delete the rows
I cant use last inserted ID since the rows are random and I dont how many it will load.
// Update
"SELECT count(*) from table" - the total count so far
"INSERT INTO tab_videos_watched (id , name) values (id , name)" - this is random can be 3400 or 5060 or 1200
"DELETE FROM table WHERE idtable <= $table_count"
If id is auto incremented, then you should use like:
select max(id) from my_table;
Read this maxId into a variable and then use when issued a delete query like:
delete from my_table where id <= ?;
Replace query parameter with the last found maxId value.
Alternatively you can define a column last_inserted as datetime type.
Before next insertions, select it into a local variable.
select max(last_inserted) as 'last_inserted' from my_table;
And after insertions are made, use the last_inserted to delete records.
delete from my_table where last_inserted <= ?;
Replace query parameter with the last found last_inserted value.