Is there a way or an option available in MySQL to fix the size of a table? Which will work as a circular buffer and overwrites the old data whenever a new data gets inserted. This is useful when an application is collecting the stats and a month old data becomes no longer useful.
I know programmatically this is possible but I don't want to do that, hence this request.
BTW, this is similar to a feature called capped collection in MongoDb.
If you want to throw away last month's data, just use the day-of-the-month in your primary key. Last month's "26" will be overwritten by next month's "26".
I don't believe there is a specific option to achieve this, however, you could make it work using a simple trigger. (I know it's a programmatic way but I believe it is the only pure-sql option in mysql)
CREATE TRIGGER `CapTable` BEFORE INSERT ON `MyTable` FOR EACH ROW BEGIN
SET #NumRows = (SELECT COUNT(*) FROM MyTable);
IF #NumRows > 1000 THEN
DELETE FROM MyTable ORDER BY id LIMIT 1;
/* delete the oldest row, assuming id is auto_increment */
END IF;
END;
Related
I have a table in MySQL with a field "Ordering" These are just auto incremented numbers. Now I wonder if there is a query to change the values from the last to the first...
So the entry with ordering 205 should become 1, 204 -> 2 and so on...
It's actually not an auto-increment. The problem is I started adding projects from the current website. From page 1 to page 20, but the first item on page 1 is the latest. The way I added the new projects, the newest is on the last page..
If the ordering field is switched, the new items added will be correctly numbered again and added to the front page. It's just a wrong way I started adding old projects...
Structure
Examples of the content
I can't comment due to limitations, but i really agree with #Abhik Chakraborty.
You don't want to do this. Just use the order by as he suggested.
Example:
SELECT * FROM tableName
ORDER BY columnName DESC;
Just in case you would like to know more about it: http://www.w3schools.com/sql/sql_orderby.asp
Try this as one statement call:
SET #MaxSort := (SELECT MAX(Ordering) FROM MyTable);
UPDATE MyTable t set t.Ordering = (#MaxSort + 1 - t.Ordering);
This will work if field doesn't have unique constraint.
But this field, should not be an auto_increment field at first place. Auto increment is increasing NOT decreasing counter. Except if you just try to fix existing data and the new records will be increasing.
Additional explanation
Thanks for pointing it out. Multiple query inside single query statement doesn't work with php_mysqli and it is not used because of potential MySQL injection attack if servers allows it. Maybe you can setup PHPMyAdmin to use PHP PDO.
I can use multiple queries, but I'm using PHP PDO or DBeaver database manager.
I can only suggest to supply MaxSort manually (since this is one time job anyway):
UPDATE
MyTable t
set
t.Ordering = 254 - t.Ordering + 1;
How can I automatically empty a MySQL database when it reaches a 100 records/rows?
The database gets bigger really quick and I can't empty it all of the time because of school (I can't use my laptop there).
When there is a lot of records in the table, the action of the form will take longer to finish that's why I want the records to be deleted when reached 100 records.
I am new to the MySQL things & I would really appropriate an answer that will solve my problem :)
The database name is: db181894_names
The table is: Names
MySQL code: jsfiddle.net/LFNHr/
Try to make a restriction on adding a new record to a table.
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE INSERT
ON table1
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO #cnt FROM table1;
IF #cnt >= 100 THEN
TRUNCATE TABLE table1;
END IF;
END
$$
DELIMITER ;
Note, that COUNT operation may be slow on big InnoDb tables.
The easiest way to delete records after 100 would be to have an int ++ each time one is added, or a list that keeps track of the Primary Keys as they are added.
That being said, like most of the other people have stated, 100 records is a grain of sand in the desert. If I had to make a guess, the problem most likely lies with your query, or within the code that is making the query.
If you are doing something like:
SELECT * FROM things
foreach (item in items){
SELECT * FROM things // again
}
this would cause an issue. Could you post your code and a mock version of one of your records?
EDIT:
Yes, from the looks of your code you are doing a select, and then for each item returned from the query it does another query to the API (which is actually a second query ... just not locally).
If you did a query against your Likers table, and built another table called API_Results and populated as much of the data with information you already pulled from facebook and use API for what you haven't seen yet ... it will most likely go a lot faster.
So for example, you build a second table in your db w/ all the fields you are collecting from the API and then a method for requesting said data from your local db if_exists ... and if not it pulls it from API to populate your local copy as well as the page you are building.
RE-EDIT:
tuples1 = SELECT * FROM Likers
foreach( item in tuples1):
tuples2 = SELECT * from API_Results WHERE primarykey_in_tuples1 == field_in_API_Results
if(tuples2 == NOTHING):
// Grab API From FaceBOok
// INSERT API_Results (value, names, in, table) VALUES (some, values, from, facebook)
// Generate Page from Values
else:
// Generate Page from tuples2
tell me if this makes sense - Caffeine
I'd like to write a trigger that checks top value in column (table consists of 4 double columns and one of them acts as a primary key (value within that field should always be bigger then previous entry)). Now is there a way to compare a top value of id column with new value that should be inserted, and rollback transaction if value of new id is equal or lower then previous top value(by using sql triggers of course).
Thank you in advance.
One and most easy way I found is to check if you get any result. I mean this:
if (SELECT COUNT(*) FROM tbl_name WHERE id = id_you_want_check >= 1) {
rollback;
}
If you know to use triggers in mysql or whatever DBMS you are using (look at the documentation of your DBMS).
PS: As said Colin, next time post your SQL DBMS to easily find an appropiate solution for you. ;)
I would like to store random numbers in one MySql table, randomly retrieve one and insert it into another table column each time a new record is created. I want to delete the retrieved number from the random number table as it is used.
The random numbers are 3 digit, there are 900 of them.
I have read several posts here that describe the problems using unique random numbers and triggering their insertion. I want to use this method as it seems to be reliable while generating few problems.
Can anyone here give me an example of a sql query that will accomplish the above? (If sql query is not the recommended way to do this please feel free to recommend a better method.)
Thank you for any help you can give.
I put together the two suggestions here and tried this trigger and query:
CREATE TRIGGER rand_num before
INSERT ON uau3h_users FOR EACH ROW
insert into uau3h_users (member_number)
select random_number from uau3h_rand900
where random_number not in (select member_number from uau3h_users)
order by random_number
limit 1
But it seems that there is already a trigger attached to that table so the new one cause a conflict, things stopped working until I removed it. Any ideas about how accomplish the same using another method?
You are only dealing with 900 records, so performance is not a major issue.
If you are doing a single insert into a table, you can do something like the following:
insert into t(rand)
select rand
from rand900
where rand not in (select rand from t)
order by rand()
limit 1
In other words, you don't have to continually delete from one table and move to the other. You can just choose to insert values that don't already exist. If performance is a concern, then indexes will help in this case.
More than likely you need to take a look into Triggers. You can do some stuff for instance after inserting a record in a table. Refer this link to more details.
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
I have a content table in my MySQL database (a Drupal content table, for what it's worth), which has an auto incremented primary key, nid. I want to be able to implement an odd and even id solution, where content created on production has even ids and content created on dev has odd ids, to avoid id conflicts when I sync. Unfortunately, MySQL doesn't support sequences, or per-table auto increment increment values (i.e. increment by 2 only for db.node, rather than 1).
The best solution I can think of, is to have a BEFORE INSERT and AFTER INSERT trigger which sets the session value of auto_increment_increment to 2 in the BEFORE INSERT trigger, and then resets it to 1 in the AFTER INSERT trigger. Since it only sets the session variable, it shouldn't have any effect on other processes, and since it's a Drupal CMS table and nothing complicated is happening, it seems safe, even though it feels wrong.
However, I'm an intermediate MySQL Admin (at best :) ) and as I said it certainly feels hackish, so I thought I'd put this out there and see if anyone has any strong negative reactions to this, perhaps some issue I'm not foreseeing. ( And I suppose if no one does then maybe someone else will find this useful).
Here's a simple example of what you want to do - assuming there is an integer column 'seq'
in the 'my_table_name' table:
DROP trigger my_trigger_name;
CREATE TRIGGER my_trigger_name
BEFORE INSERT ON my_table_name
FOR EACH ROW
SET NEW.seq = (select ifnull(max(seq)+1,1) from source_table_name);