I have a column in my database which holds an expire time being inserted with NOW() + INTERVAL 30 MINUTE;
I need to be able to pull out minutes remaining from that column. I have no idea where to start.
Thanks in advance.
SELECT TIMESTAMPDIFF(MINUTE,NOW(),column1) AS minutes_remaining FROM table1;
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff
Note that the order of the arguments is extremely counterintuitive... to get a positive number as a result, the larger (later) datetime value is the last argument. If the second argument is >= the third, the result will be <= 0.
Related
i looking for some help about MySQL, Very easy question, but really breaked my brain for some time.
i have a table called "logs", That have "date" thing, That is INT(11) of Timestamp, So, it use timestamp actual for it.
i gonna make a script that execute a SQL command each minute, That Check ALL rows, if "date" have more/equal than 6 hours, i tired so much, and nothing for help.
Some commands i used and won't worked.
DELETE FROM logs WHERE date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 6 HOUR));
DELETE FROM logs WHERE date < NOW() - INTERVAL 6 HOUR;
Won't help, So, i asking here if you can help me, Thanks.
You can do something like that :
DELETE FROM logs
WHERE FROM_UNIXTIME(date) < UNIX_TIMESTAMP(NOW() - INTERVAL 6 HOUR);
The date "thing" is called a column. The column has a specific datatype. The question indicates that the column is datatype INT(11). And in that column is stored unix-style 32-bit integer number of seconds since 1970-01-01 UTC.
If that's all true, then the first query form is appropriate. The expression on the right side (of the less than comparison) returns an integer number of seconds.
As a demonstration, consider this expression:
SELECT UNIX_TIMESTAMP( NOW() + INTERVAL -6 HOUR ) ==> 1528450555
or, the way the original is written
SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 6 HOUR))
returns an equivalent result.
The second query can be evaluated, but the automatic conversion from DATETIME to numeric will return us an integer value like 20180608153555 (i.e. yyyymmddhhmmss), not number of seconds since the beginning of the epoch.
Consider a demonstration, DATETIME dataytpe evaluated in numeric context:
SELECT NOW() + INTERVAL -6 HOUR + 0 ==> 20180608153600
If we use that expression, compare that to an INT(11) column, and delete all rows that have an INT(11) column less than that value, it's going to delete every row in the table that has a non-NULL value in that column.
Your date column must be of Type TIMESTAMP and not INT in order to be able compare timestamps with each other properly, or you can write:
DELETE FROM logs WHERE FROM_UNIXTIME(date) < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 6 HOUR));
In my database, I have a table called 'fine', in that table I have three fields, issue_date, expiry_date and fine_amount. I want the expiry_date to be computed from the issue date. The expiry date should always have 20 days more than the issue_date, So I wrote the query as:
ALTER TABLE fine ADD
expiry_date AS DATE_ADD(CURRENT_DATE,INTERVAL 20 DAY)
But there is a syntax error. I can't seem to find the solution.
Also I want the fine_amount to be 10 * (difference in days between current date and expiry date if current days exceeds expiry date). How do I go about doing that?
You can't implement the fine logic using a computed column because the formula involves the current time which is non deterministic. From the MySQL documentation:
Literals, deterministic built-in functions, and operators are permitted. A function is deterministic if, given the same data in tables, multiple invocations produce the same result, independently of the connected user. Examples of functions that fail this definition: CONNECTION_ID(), CURRENT_USER(), NOW().
So your best bet probably is to just compute values for these columns at the time you actually select. For example:
SELECT issue_date,
DATE_ADD(issue_date, INTERVAL 20 DAY) AS expiry_date,
CASE WHEN NOW() > DATE_ADD(issue_date, INTERVAL 20 DAY)
THEN 10*DATEDIFF(NOW(), DATE_ADD(issue_date, INTERVAL 20 DAY))
ELSE 0 END AS fine_amount
FROM fine
I am trying to get data from a database between 8PM (say, today) and 2AM tomorrow.
I have been using clauses such as where hour(date_field)>=20 and hour(date_field) <23 to obtain data in the same day.
Here the date_field is datetime
All I want is to be able to tell SQL to get data after 8PM today, increment the datefield and then get data till 2AM tomorrow.
Any help will be appreciated.
The normal pattern for retrieving rows based on a datetime range is perform comparisons on the bare column, comparing the column value to constants derived from expressions.
To get rows for a single contiguous range, 8PM today to 2AM tomorrow, for example:
WHERE t.date_column >= DATE(NOW()) + INTERVAL 20 HOUR
AND t.date_column < DATE(NOW()) + INTERVAL 26 HOUR
To unpack that a little bit: NOW() returns current datetime, the DATE() function truncates the time portion to midnight, then we add back in enough hours to get '8PM today', or enough hours to get '2AM tomorrow'.
If you are meaning to retrieve multiple "8PM to 2AM" periods, for a whole series of days.
First, you'd want an upper and lower bound of the date_column to be retrieved (unless you want every possible date)
WHERE t.date_column >= '2014-08-01 20:00:00'
AND t.date_column < '2014-10-02 02:00:00'
From that, we need to filter out all of the rows that aren't between 8PM and 2AM. One convenient way to do that would be to "subtract" two hours from the datetime col, and check for hour >= 6PM.
AND HOUR(t.date_column + INTERVAL -2 HOUR) >= 18
Note that the expression involving date_column will need to be evaluated for EVERY row in the table, unless there are some other predicates that filter rows out. With a suitable index available, MySQL can use an index range scan operation for predicates of the form date_column >= const and date_column < const. (It can't do that when the column is wrapped in a function or expression.)
I have a column with timestamp, contain example value "2014-04-16 18:00:00","2014-04-17 18:00:00"....
Now, if I will call a page before "2014-04-17 12:00:00" I need this value-"2014-04-16 18:00:00"
And if I call my page after "2014-04-17 12:00:00" I need this value "2014-04-17 18:00:00".
I think my question is very complicated to understand, having complications in date & times, please check date & time properly.
I want to fetch this data from DB in mysql, The page I was saying is that where I'm going to add your mysql query.
Thanx in advance
Generalising what your asking for a bit the following will return dates from the previous day if it's before noon and dates from today if it's after noon:
SELECT date_column
FROM yourTable
WHERE DATE(DATE_SUB(NOW(), INTERVAL 12 HOUR)) = DATE(date_column);
Edit:
The WHERE clause First gets the current time (NOW()) and subtracts 12 hours. This wont affect the date unless the time is before 12. This means DATE_SUB(NOW(), INTERVAL 12 HOUR) gives us today if it's after noon and yesterday if it's before.
We then check if the date_column matches the date we've created (using the DATE function so that the time is ignored).
Adding some rows to the SELECT may help you see how these dates are built up.
I have a table 't' with date(yyyy-mm-dd), hour(1-12), minute(00-59), ampm(a/p), and timezone(pst/est) fields.
How can I select the rows that are <= now()? (ie. already happened)
Thank you for your suggestions!
edit: this does it without attention to the hour/minute/ap/tz fields:
SELECT * FROM t.date WHERE date <= now()
Here's one way to do it - combine all your seconds, minutes, etc into a date and compare to NOW(), making sure you do the comparison in the same time-zone. (Untested):
SELECT *
FROM t
LEFT JOIN y ON t.constant=y.constant
WHERE CONVERT_TZ(STR_TO_DATE(CONCAT(date,' ',hour,':',minute,' 'ampm),
'%Y-%m-%d %l:%i %p' ),
timezone,"SYSTEM") < NOW();
If your hour is 01 - 12 not 1-12 then use %h instead of %l in the STR_TO_DATE.
The STR_TO_DATE tries to stick your date and time columns together and convert them into a date.
The CONVERT_TZ(...,timezone,"SYSTEM") converts this date from whatever timezone is specified in the timezone column to system time.
This is then compared to NOW(), which is always in system time.
As an aside, perhaps you should make a single column date using MySQL's date datatype, as it's a lot easier to do arithmetic on that!
For reference, here is a summary of very useful mysql date functions where you can read up on those featuring in this answer.
Good luck!
SELECT * FROM t
WHERE `date`<=DATE_SUB(curdate(), INTERVAL 1 DAY)
OR (
`date`<=DATE_ADD(curdate(), INTERVAL 1 DAY)
AND
CONVERT_TZ(CAST(CONCAT(`date`,' ',IF(`hour`=12 AND ampm='a',0,if(ampm='a',`hour`,`hour`+12)),':',`minute`,':00') AS DATETIME),'GMT',`timezone`)<=NOW()
)
Rationale for date<=DATE_[ADD|SUB](curdate(), INTERVAL 1 DAY):
The fancy conversion is quite an expensive operation, so we don't want it to run on the complete table. This is why we pre-select against an UNCHANGED date field (possibly using an index). In no timezone can an event being more than a day in current timezone's past be in the future, and in no timezone can an event more than a day in the curent timezone's future be in the past.