Mysql Add days onto date from two different columns - mysql

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;

Related

MySQL dynamic date change

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?

How to count occurrences in date range for each day on a column

I have a problem for which a 15 minute search on SO couldn't get an answer. I have a database with a table called bugs, which is used to store some info about bugs in a system we are developing. Columns of importance are open_date, close_date and status of severity of the bug introduced. I need to make an SQL statement to display counted number of opened bugs for each of dates from a range of dates which is entered. A bug is considered open on “2012-01-01” if it is created on or
before “2012-01-01” (i.e. the same day) and closed on or after “2012-01-02” (i.e. day after that date).
I have made an sql for finding unit functionality of the requirement:
SELECT COUNT(DATE(Open_Date)) BugsOpen
, DATE(Open_Date) Dated
FROM bugs
WHERE DATE(open_date) <= (STR_TO_DATE('21/10/17','%d/%m/%Y'))
AND DATE(close_date) >= (DATE_ADD(STR_TO_DATE('21/10/17','%d/%m/%Y'),INTERVAL 1 DAY))
OR close_date IS NULL);
Which is working but I need this in like a function call or stored procedure call, ex. showBugs('21/10/17 - 29/10/17'), to display for each of the dates in the range input in this function/procedure.
I have found a way to extract to and from dates.
SELECT SUBSTRING('21/10/17 - 29/10/17', -19, 8) as from_date,
SUBSTRING('21/10/17 - 29/10/17' FROM 12) as to_date;
But I am really having trouble writing a simple procedure. I have started writing some code:
DROP PROCEDURE IF EXISTS showBugs;
CREATE DEFINER = 'root'#'localhost' PROCEDURE showBugs(rangeOfDates TEXT)
BEGIN
SET #from_date = SUBSTRING(rangeOfDates, -19, 8);
SET #to_date = SUBSTRING(rangeOfDates FROM 12);
REPEAT SET #from_date
END REPEAT;
END;
call showBugs('21/10/17 - 29/10/17');
I am really in a rut here and would be grateful if someone is to help me either with stored procedure or function implementation.

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.

Converting UTC 12 hour time format to indian time using Mysql

I am writing an event scheduler in Mysql for generating tickets 3 hour prior to the user travel time. Mysl is installed in server where the server time is in UTC and 12 hour format with 5:30 hour difference with IST time. I have one user whose travel time is 7:30 in the morning, so i need to generate ticket for this user at 4:30 in the morning. I am getting current server time and converting to IST and comparing travel time and current converted time difference is 3 hours. But some how its failing and always ticket creating at 10 am in the morning. Below is my complete event writtent in Mysql,
DELIMITER $$
ALTER EVENT `Auto_Generated_Ticket` ON SCHEDULE EVERY 1 MINUTE STARTS CURRENT_TIMESTAMP ON COMPLETION PRESERVE ENABLE DO BEGIN
DECLARE UserId INT;
DECLARE v_finished INT DEFAULT 0;
DECLARE GetDate DATE DEFAULT DATE(NOW());
/*get all active user's who's tariff enddate is > today and available journeys > 0 and pass-status=4(delivered)*/
DECLARE ActiveUserId CURSOR FOR
SELECT UT.user_id FROM `um.user_trs.tariff` UT
INNER JOIN `um.user` U ON U.user_id=UT.user_id
INNER JOIN `um.user_ps.pass` UP ON UP.user_id=UT.user_id
INNER JOIN `ps.pass` P ON P.pass_id=UP.pass_id
WHERE UT.end_date >=DATE(NOW()) AND UT.available_journeys > 0 AND UT.current_balance>0 AND P.status_id=4
GROUP BY UT.user_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished=1;
SET #GetTime= DATE_FORMAT(NOW(),'%Y-%m-%d %h:%i:%s %p');
OPEN ActiveUserId;
get_userid:LOOP
FETCH ActiveUserId INTO UserId;
IF v_finished=1 THEN
LEAVE get_userid;
END IF;
SET #StartTime=(SELECT RS.start_time FROM `um.user_rm.route` UR
INNER JOIN `rm.route_schedule` RS ON RS.route_schedule_id=UR.route_schedule_id
WHERE UR.user_id=UserId
ORDER BY ABS( TIMEDIFF( RS.`start_time`, TIME(CONVERT_TZ(#GetTime,'+00:00','+05:30')) ) ) LIMIT 1);
SET #TimeDiff=(HOUR(TIMEDIFF(#StartTime,TIME(CONVERT_TZ(#GetTime,'+00:00','+05:30')))));
/*if time difference between current time and schedule start time is 3 hours then generate ticket for the user for that particular schedule*/
IF (#TimeDiff =3) THEN
/*IF (#TNumber IS NULL) THEN*/
IF NOT EXISTS(SELECT ticket_number FROM `um.user_ts.ticket` WHERE route_id=#RouteId AND route_schedule_id=#RoutScheduleId
AND user_id=UserId AND DATE(date_of_issue)=#ISTDATE) THEN
INSERT INTO `um.user_ts.ticket`
(
`user_id`,`route_id`,`route_schedule_id`,`ticket_number`,`date_of_issue`,`is_cancelled`,
`amount_charged`,`user_tariff_id`,`opening_balance`,`is_auto_generated`
)
VALUES
(
UserId,#RouteId,#RoutScheduleId,#TicketNumber,CONVERT_TZ(UTC_TIMESTAMP(),'+00:00','+05:30'),
FALSE,#PerJourneyCost,#UserTariffId,#TariffCurrentBalance,1
);
END IF;/*end of route and schedule check*/
END IF; /*end of time difference check*/
END LOOP get_userid;
CLOSE ActiveUserId;
END$$
DELIMITER ;
Please let me know if any other way to convert time or any mistake which i am not noticing in the above query.
Regards
Sangeetha
There is a dedicated mysql command to do so. CONVERT_TZ(dt,from_tz,to_tz)
See here https://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_convert-tz
From their docs:
CONVERT_TZ() converts a datetime value dt from the time zone given by
from_tz to the time zone given by to_tz and returns the resulting
value
Maybe the warning applies to you ?
Warning
Do not use a downloadable package if your system has a zoneinfo
database. Use the mysql_tzinfo_to_sql utility instead. Otherwise, you
may cause a difference in datetime handling between MySQL and other
applications on your system.
I would break it down to a minimalistic example and see if this works.
Here's how I would do it to test the basics:
Simple example:
SELECT CONVERT_TZ('2016-05-24 12:00:00','GMT','MET');
So you could build a query to determine the timediff like this:
HOUR(TIMEDIFF(
CONVERT_TZ('2016-05-24 12:00:00','GMT','MET'),
'2016-05-24 12:00:00'
))

MySQL date intervals generation

I am working with MySQL database and I have to generate date intervals for specified period(specified by start and stop date) with specified step(for example one day).
I have written a stored procedure to generate intervals, to create a temporary table and to populate this table with intervals.
DELIMITER $$
CREATE PROCEDURE showu(IN start date, IN stop date)
BEGIN
CREATE TEMPORARY TABLE intervals(single_day DATE);
next_date: LOOP
IF start>stop THEN
LEAVE next_date;
END IF;
INSERT INTO intervals(single_day) VALUES(start);
SET start = DATE_ADD(start, INTERVAL 1 DAY);
END LOOP next_date;
END$$
DELIMITER ;
I want to use this temporary table in join queries. However I faced with a problem. When I call procedure call showu('2008-01-09', '2010-02-09'); it is executing approximately 30 seconds. The question why it is executing so long? Is it possible to improve it? If this solution is wrong how can I resolve my problem in different way?
From comments:
2 big problems: 1. I don't know exactly value of step(one day or one month or one hour).
Create one big table like this once (not temporary):
full_date | year | month | day | full_time | hour | minute | is_weekend | whatever
----------------------------------------------------------------------------------
...
Create as much indexes as needed and you will have a very performant a powerful swiss knife for all sorts of reports.
Note: You might consider not having time and date in the same table. This is just to simplify the example.
Your second problem
I will clog my database with not model data.
is no problem. Databases are there to hold data. That's it. If you have problems with space or whatever, the solution is to get more space, not to limit your ability to work efficiently.
That being said, here's some examples how to use this table.
You need dates:
SELECT
*
FROM
(
SELECT full_date AS your_step
FROM your_new_swiss_army_knife
WHERE `year` = 2012
GROUP BY full_date
) dates
LEFT JOIN your_tables_that_you_want_to_build_a_report_on y ON dates.your_step = y.date
Same with months:
SELECT
*
FROM
(
SELECT CONCAT(year, '-', month) AS your_step
FROM your_new_swiss_army_knife
WHERE full_date BETWEEN this AND that
GROUP BY year, month
) dates
LEFT JOIN your_tables_that_you_want_to_build_a_report_on y ON dates.your_step = CONCAT(YEAR(y.date), '-', MONTH(y.date))