Auto add days to datetime as each days passes in mysql - mysql

I want to make a column in mysql database that when user login first time in system, it stores that datetime in mysql table. And since that day in other column days will add according to his register date. Like 1, 2, 3,....and so on. So, is there any way I can achieve the results? Please guide me soon.

You can do this with just one column (to hold the registration / first login date) and the DATEDIFF function:
CREATE TABLE users (
ID int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
registered_at datetime NOT NULL,
PRIMARY KEY (ID)
);
INSERT INTO users SET
name = 'myname',
registered_at = NOW();
SELECT registered_at, DATEDIFF(NOW(), registered_at) AS days_since
FROM users
WHERE name = 'myname';

Related

Delete all rows older than 30 days with single query once in a month MYSQL [duplicate]

Basically I have a MySQL database with a table that stores requests from the users of my website. I would like to automatically perform a query that removes all completed requests (completed means that the column Status = 3) older than 180 days basing on the column ArchivingDate.
My Requests table:
Requests(
RequestID INT AUTO_INCREMENT PRIMARY KEY,
Ticket VARCHAR(40) NOT NULL UNIQUE,
RequestDate DATETIME NOT NULL,
ReplacementOrRefund INT NOT NULL,
ItemName VARCHAR(200) NOT NULL,
Total NUMERIC(15, 2) NOT NULL,
AccountName VARCHAR(200) NOT NULL,
Email VARCHAR(254) NOT NULL,
BillingAddress VARCHAR(200) NOT NULL,
OrderNumber VARCHAR(50) NOT NULL,
OrderDate DATETIME NOT NULL,
DeliveryDate DATETIME NOT NULL,
WhoSigned VARCHAR(200),
WhereLeft VARCHAR(200),
Status INT NOT NULL,
ArchivingDate DATETIME,
PayPalTransactionID VARCHAR(100),
Toggle TINYINT(1) NOT NULL,
StoreID_FK INT,
FOREIGN KEY (StoreID_FK) REFERENCES Stores(StoreID)
);
I have already written the query to remove rows that are older than 180 days:
$remove = "UPDATE Requests SET Toggle = 0 WHERE Status = 3 AND ArchivingDate < DATE_SUB(NOW(), INTERVAL 180 DAY)";
NOTE: I do not remove data from the table, I simply "hide" it by setting the column Toggle to 0.
Question: How do I automatically make MySQL perform this query once a day (if it's possible)?
Thank you very much in advance!
you can create a stored procedure to delete the records based on your criteria of 180 days on "RequestDate" and schedule your stored procedure on daily basis.
Now MySQL will handle the deletion automatically.
yes, it's possible, see this article: http://www.sitepoint.com/how-to-create-mysql-events/
It depends witch OS you have.
Linux
Use file /etc/crontab, add line where specify time and command what to execute.
The columns in crontab file are:min,hour,day of month,month,day of week,run as user, command.(Colums are seperated by space)
For example:
30 22 * * * apache php /usr/remove_old.php
It will execute every evening in 22:30.
It is good practice to put the execution result to log file.
30 22 * * * apache php /usr/remove_old.php >> \var\log\removed_requests.log 2>&1
The you can analyze later if somethings goes wrong.
Windows
You can use Task Scheduler programm.

how to check to modify the definition

CREATE TABLE Hotel
(roomNum INTEGER NOT NULL,
arrD DATE NOT NULL,
depD DATE NOT NULL,
guestName CHAR(30) NOT NULL,
PRIMARY KEY (roomNum, arrDate));
how can I modify the definition to keep a check so that no room is booked before the departure date of previous allocation.
You can do an INSERT with a NOT EXISTS clause to check the validity of the date:
INSERT INTO Hotel (roomNum, arrD, depD, guestName)
SELECT 1, '2017-02-08', '2017-02-11', 'Tim Biegeleisen'
FROM dual
WHERE NOT EXISTS (SELECT * FROM Hotel WHERE roomNum = 1 AND depD > '2017-02-08')
I don't think that modifying the table definition will make it possible to enforce your logic.

Explicitly specifying value for an auto-incremented column in MySql

MySql forces me to specify value for an auto-incremented column. I do not understand why i need to do that.
I have created a table with the following columns
CREATE TABLE IF NOT EXISTS Aask
( task_id INT(11) AUTO_INCREMENT,
SUBJECT VARCHAR(45) DEFAULT NULL,
start_date DATE DEFAULT NULL,
end_date DATE DEFAULT NULL,
description VARCHAR(200) DEFAULT NULL,
PRIMARY KEY (task_id)
);
After creating the above table, when i try to insert rows using
INSERT INTO flask
VALUES ('Subject1','1892-12-27','1994-11-29','detailed description'),
('Subject2','1992-01-17','1694-11-31','HTML view');
I get an error message which says
Query: INSERT INTO flask VALUES ('Subject1','1892-12-27','1994-11-29','detailed description'), ('Subject2','1992-01-17','1694-11-31','H...
Error Code: 1136
Column count doesn't match value count at row 1
I know there are 5 columns in the table and i have given only 4 values in value list but why am i forced to mention value for auto increment column?
This may sound basic to most of you guys but i am just getting started with MySql so any help here would be greatly appreciated.
Use this insert
INSERT INTO flask (SUBJECT, start_date, end_date, description ) values 'Subject1','1892-12-27','1994-11-29','detailed description');

Values within primary key occasionally changes over time

I got some data defined in a table in a MySQL database like this
CREATE TABLE `T_dev` (
id VARCHAR(20) NOT NULL,
date DATETIME NOT NULL,
amount VARCHAR(9) DEFAULT NULL,
PRIMARY KEY (id,date)
);
I then insert a record, for example
INSERT INTO T_dev VALUES
('10000','2009-08-05 23:00:00','35')
However, one month later I get a report that tells me that this exact record should have amount equal to 30, thus
INSERT INTO T_dev VALUES
('10000','2009-08-05 23:00:00','30')
However, that can´t be done because of the primary key I´ve defined. I would like to overwrite the old record with the new one, but not really change my primary key. Any suggestions?
Thanks.
Alexander
Since the record already exists, you don't use the INSERT statement. Instead use an UPDATE statement to change the value to 30 for that specific id and date combination:
UPDATE T_dev SET amount = '30'
WHERE id = '10000' AND date = '2009-08-05 23:00:00'
Just an observation, your table is a little out of the norm. Typically primary keys are of type INT and your amount would probably be better off as a DECIMAL.
use an update statement
UPDATE T_dev
SET amount = 30
WHERE id=10000 AND date = '2009-08-05 23:00:00'

Using UNIQUE indices with NULL fields in MySQL?

I can check, periodically, for a list of users that are currently online. I want to turn this into something useful like a list of entries per user with login / logout time. There is no other way to determine this information apart from checking who is currently online.
After some thinking I came up with something like this:
CREATE TABLE onlineActivity (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR (32) NOT NULL,
login_time DATETIME NOT NULL,
logout_time DATETIME NOT NULL,
time SMALLINT (3) NOT NULL DEFAULT 0,
online BOOL DEFAULT NULL,
UNIQUE (name, online),
PRIMARY KEY (id)
) ENGINE = MyISAM;
I run this query every few minutes to add/update names in the activity list:
INSERT INTO onlineActivity (name, login_time, logout_time, online)
SELECT name, now(), now(), true FROM onlineList ON DUPLICATE KEY UPDATE logout_time = now()
And this query is run for every user that has logged out:
(the names are determined by comparing two adjacent online lists, the current one and the previous one)
UPDATE onlineActivity SET online = NULL WHERE name = ? AND online = 1
The questions:
I'm worrying that using a NULL field (online) in a UNIQUE index is a bad idea, and will hurt performance. I figure that MySQL might have to do a full scan of all the online's (instead of using an index) for each name to find one that is not NULL. Could someone clarify if that is the case here? I couldn't find any information on how MySQL deals with this sort of situation.
Do other database systems (PostgreSQL, SQLite) behave differently then MySQL in this regard?
should I instead of the first query, run two queries for each name, to see if a specified user is currently online, and act accordingly on that?
I thought of this design because I wanted to minimize the amount of queries used, is this a flawed idea in itself?
This table will be getting around 300~500k new records per day. Is there something else I can do to lessen the performance decrease?
I want to store a full history of user activity, not a single entry.
I am not sure why you have a unique on name and online since what you are trying to do is create a list of online activity. Putting a unique key as you have specified will mean that you can only have a name in there three times, one for each state (null, true, false).
What you are effectively doing is trying to create a history table in which case to use your current method of populating the table you should put a unique key on (name, logout_time) with a null logout_time indicating a currently logged in user (since you would only want one logout time that is null).
Something like this:
CREATE TABLE onlineActivity (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR (32) NOT NULL,
login_time DATETIME NOT NULL,
logout_time DATETIME NULL,
time SMALLINT (3) NOT NULL DEFAULT 0,
online BOOL not null DEFAULT false,
UNIQUE (name, logout_time),
PRIMARY KEY (id)
) ENGINE = MyISAM;
Then run this on a schedule to update the table
INSERT IGNORE INTO onlineActivity (name, login_time, logout_time, online)
SELECT name, now(), null, true FROM onlineList
And this on user logout
UPDATE onlineActivity SET online = false, logout_time = now() WHERE name = ? AND logout_time = null