MySQL dynamic date change - mysql

I want to create table with name "dynamicdate" in which first column name is "datecolumn" which will contain 15 rows i.e. first row should represent today's date for example 08/08/2017 and following column shows subsequent date for example, 08/09/2017, 08/10/2017 till 15th row contains 08/23/2017.
Question 1: How do I fill 15 rows in a column with consecutive date simultaneously.
Now, for example date becomes 08/09/2017 (because august 8 is over) is the today'date and 08/24/2017 is date of 15th day.
Question 2: How do i update database everyday dynamically i.e. without querying database.

This you can do by creating a job. Every morning or night schedule this Job.
A job will execute this procedure "p_Update_dynamicdate".
create proc dbo.p_Update_dynamicdate
as
Begin
Declare #date as datetime, #count as int
set #date =getdate()
set #count =1
truncate table dynamicdate --Delete old data
while #count<=15
Begin
insert into dynamicdate(Ddate)
select Dateadd(d,#count,getdate())
set #count=#count+1
End
End

Solution to problem #1 :
Already solved on StackOverflow :
MySQL - How can I add consecutive dates to many existing records?
Solution to problem #2 :
Please look at Schedule and events on MySql documentation :
https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html
syntax: CREATE EVENT my_event
ON SCHEDULE
EVERY 1 DAY
STARTS '2014-04-30 00:20:00' ON COMPLETION PRESERVE ENABLE
DO
# Your Update query
Please refer to below links for similar problem solution :
https://dba.stackexchange.com/questions/64208/scheduling-an-event-every-day-at-a-given-time
How to schedule a MySQL query?

Related

Adding days to monthly events in MySQL

DELIMETER $$
CREATE EVENT loan_balance ON SCHEDULE EVERY '1' MONTH AND '5' DAYS
DO BEGIN UPDATE users SET loan_balance = total_loans_collected -
total_loans_paid;
END$$
DELIMETER;
Hello! I want to update this table on the 5th of every month and not just monthly. The "AND '5' DAYS isn't making it work.
You need a slightly different ON SCHEDULE phrase.
AT '2018-04-01 03:01' + INTERVAL 5 DAY EVERY MONTH
fires your event at 03:01 local time on the fifth day of every month.
03:01 is a good time for a scheduled job because it doesn't get messed up by standard-time / daylight-time switchovers.
Instead of using a trigger to update the loan_balance column, you can turn it into a generated column.
ALTER TABLE users MODIFY COLUMN loan_balance INT GENERATED ALWAYS AS
(total_loans_collected - total_loans_paid) STORED;
Unless I'm missing something, I believe this is the most optimal approach, and it is certainly easier to maintain.

Mysql Add days onto date from two different columns

Hi my problem relates to adding days onto a date from two different tables in MySql in the Mamp environment.
Membership type to Membership transaction is 1 to many
The link is type_id
Date is in yyyy/mm/dd format also as this is the only format that Mamp will allow from my research.
I want a new end date column that links to the column duration from the membership type table. I want to add Duration_day onto start_date to produce an end date that matches up with the type_id. (So they link up to give the correct end date)
I want it to be automatically calculated when the start date and type-id are saved
Any help would be appreciated
Thanks
You will need a trigger on INSERT/UPDATE - a calculated column (for MySQL v5.7.6+) will not work in your case (it can only refer to columns in the same table).
The 2 triggers may look like this
CREATE DEFINER = 'root'#'%' TRIGGER `m_duration_ins_tr1` BEFORE INSERT ON `membership`
FOR EACH ROW
BEGIN
DECLARE duration INTEGER;
SELECT m_duration INTO duration FROM membership_type WHERE id = NEW.type_id;
SET NEW.end_date := DATE_ADD(NEW.start_date, INTERVAL duration DAY);
END;
CREATE DEFINER = 'root'#'%' TRIGGER `m_duration_ins_tr1` BEFORE UPDATE ON `membership`
FOR EACH ROW
BEGIN
DECLARE duration INTEGER;
SELECT m_duration INTO duration FROM membership_type WHERE id = NEW.type_id;
SET NEW.end_date := DATE_ADD(NEW.start_date, INTERVAL duration DAY);
END;

How do I clear old entries from a MySQL database table?

I have a MySQL database with one big table in it. After a while, it becomes too full and performance degrades. Every Sunday, I want to delete rows whose last update is older than a certain number of days ago.
How do I do that?
Make a Scheduled Event to run your query every night. Check out Event Scheduler as well.
CREATE EVENT `purge_table` ON SCHEDULE
EVERY 1 DAY
ON COMPLETION NOT PRESERVE
ENABLE
COMMENT ''
DO BEGIN
DELETE FROM my_table WHERE my_timestamp_field <= now() - INTERVAL 5 DAY
END
What is the table design? Do you have a column with a timestamp?
Assuming you do, you could use that timestamp value with a datediff(your_date,CURDATE()) in a delete command.
Delete from table where datediff(date_col, CURDATE ()) > your_num_days.
Self Answer
Make a web server that sends the following SQL to the database every weekend:
DELETE FROM table WHERE timestamp < DATE_SUB(NOW(), INTERVAL 7 DAY);
or
DELETE FROM table
WHERE timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))
I might need locking to prevent accumulation of jobs, like so:
DELIMITER //
CREATE EVENT testlock_event ON SCHEDULE EVERY 2 SECOND DO
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('testlock_event');
END;
IF GET_LOCK('testlock_event', 0) THEN
-- add some business logic here, for example:
-- insert into test.testlock_event values(NULL, NOW());
END IF;
DO RELEASE_LOCK('testlock_event');
END;
//
DELIMITER ;
Final answer:
CREATE EVENT `purge_table` ON SCHEDULE
EVERY 1 DAY
ON COMPLETION NOT PRESERVE
ENABLE
COMMENT ''
DO BEGIN
IF GET_LOCK('purge_table', 0) THEN
DELETE FROM table WHERE timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY));
END;
Maybe you can provide more information on how you are pushing the data to the DB and how you are working on the DB in general? Therefore we can help you and don't have to struggle with the dark...
I'll provide an easy solution: It's kind of workaround, but works:
Everytime you touch the data you update a time stamp in the updated rows.
Therefore you could easily filter them out every sunday.
UPDATE
The answer, the author provided by himself, was discussed at Stackoverflow and seems not to work in exactly that way, compare the discussion.

phpmyadmin logic command to unpublish records in table stored before set period of time

I have date as DB column
Can someone advise on a command in phpmyadmin which will unpublish all records more than 6 month old
For Instance -
v_id : unique record value given to every record
Adddate : Date field - values stores as 2015-11-23 09:39:28 (Year-Month-Date Time)
v_status : 1 means published and 0 means unpublished
Table name xyz_used
What command can i run in my phpadmin so that it can unpublish i.e make V_id record status i.e. v_status as 0 having adddate as before 2015-05-31 in table xyz_used
Pls am not aware of command at all - hence asking question for help
thanks
first of all phpmyadmin is a tool or webapp to access mysql databases. you can say it is a client utility.
Second
To update a table you will need to write Update Sql Query where you can put the date and can set the status.
query would be like
Updaate <tbl> set v_status = 0 where datefield < date_sub(now(), interval 6 month);

Correct MySQL Structure for a Time Range for Query Optimization?

I have a scenario where I want to be able to SELECT rows from a MySQL table, but exclude rows where the current time-of-day is inside a time-range.
Example:
The "quiet" period for one row is 10pm - 8:30am.
My SQL SELECT statement should not return that row if the current server time is after 10pm or before 8:30am.
Example 2: The "quiet period" is NULL and ignored.
Example 3: A new row is created with a quiet period from 9:53am to 9:55am. If the current server time is in that 2-minute window, the row is not returned by the SELECT.
My question:
What data format would you use in the database, and how would you write the query?
I have thought about a few different approaches (defining start_time as one column and duration as another, defining both in seconds... or using Date stamps... or whatever). None of them seem ideal and require a lot of calculation.
Thanks!
I would store the start and end dates as MySQL native TIME fields.
You would need to consider ranges that span midnight as two separate ranges but you would be able to query the table like this, To find all current quiet periods
SELECT DISTINCT name FROM `quiet_periods`
WHERE start_time<=CURTIME() AND CURTIME()<=end_time
Or to find all non-active quiet periods
SELECT name FROM quiet_periods WHERE name NOT IN (
SELECT name FROM `quiet_periods`
WHERE start_time<=CURTIME() AND CURTIME()<=end_time
)
So with sample data
id -- name -- start_time -- end_time
1 -- late_night -- 00:00:00 -- 08:30:00
2 -- late_night -- 22:00:00 -- 23:59:59
3 -- null_period -- NULL -- NULL
4 -- nearly_10am -- 09:53:00 -- 09:55:00
At 11pm this would return
null_period
nearly_10am
from the second query.
Depending on performance and how many rows you had you might want to refactor the second query into a JOIN and probably add the relevant INDEXes too.