Mysql search between two date with time - php

how to search between two date , when date format in database like :
2015-10-10 02:23:41 am
i just want to search between two date with format :
2015-10-10
without
02:23:41 am
any ideas please ?

Your question isn't completely clear. But, I guess you hope to find all the rows in your table where Date occurs on or after midnight on 2015-08-05 and before midnight on 2015-09-11 (the day after the end of the range you gave in your question.
Those two search criteria will find all the rows with Date values in the range you specified. (I'm ignoring the 02 at the end of 2015-09-10 02 in your question because I can't guess what it means, if anything.)
Try this query:
SELECT *
FROM table
WHERE `Date` >= '2015-08-05'
AND `Date` < '2015-09-10' + INTERVAL 1 DAY
This has the benefit that it can exploit an index on the Date column if you have one, so it can be fast.
You could write
SELECT *
FROM table /* slow! */
WHERE DATE(`Date`) BETWEEN '2015-08-05' AND '2015-09-10'
That's slightly easier to read, but the WHERE condition isn't sargable, so the query will be slower.
Notice that the beginning of the range uses >= -- on or after midnight, and the end of the range uses < -- before midnight.
Pro tip: Avoid the use of reserved words like DATE for column names. If you make mistakes writing your queries, their presence can really confuse MySQL, not to mention you, and slow you down.

May I suggest:
select * from table where cast(date as date) between '2015-08-05' and '2015-09-10'
When your where clause is based on a timestamp, but you're using date as the parameters for your between, it excludes anything that happens on the second date unless it happened precisely at midnight.

When using the end date for the range, include the time of the end of the day:
SELECT *
FROM YourTable
WHERE date BETWEEN '2015-08-05' AND '2015-09-10 23:59:59'

Related

Select * matches where current date bigger than now and current time bigger than now

Working with dates and times has always been a challenge for me, I have done plenty of research on SE regarding mysql date queries but have not found anything concrete enough to help me with my problem.
Im working on app for work which needs to display all matches which has not expired, a match expires when the date has passed AND time has passed.
Example:
A match could still be active even though the match day is today providing that the time has not past...I think you get what I mean?
The above is the simple part the hard part is the implementation.
I could go:
SELECT * FROM matches WHERE match_date >= CURDATE();
MY Question(s)
How would I modify the above query that it includes a time function aswell?
Would you say the above query regarding DATE is the best / most effective query I can use for what I want to achieve?
Any help / advice appreciated
I think this does what you want:
SELECT *
FROM matches
WHERE match_date > CURDATE() OR
( match_date = CURDATE() and match_time > CURTIME() );
Note: You should really store the date and time in a single field. Then you could do:
SELECT m.*
FROM matches m
WHERE match_datetime >= now();
Much simpler. And more likely to use an index.
You can combine DATE and TIME with the TIMESTAMP() function.
SELECT * FROM matches WHERE TIMESTAMP(match_date, match_time) >= NOW()
In order to use an index at least for match_date you can add a redundant condition match_date >= CURDATE().
SELECT *
FROM matches
WHERE match_date >= CURDATE()
AND TIMESTAMP(match_date, match_time) >= NOW()
The first condition will ignore everything before today using an index.
As other already mentioned things get easier if you use a DATETIME or a TIMESTAMP column. If you use MySQL 5.7.6 (or greater), you can also create a computed/generated column and index it.

Compare date and datetime

I want to compare a datetime from sql and the todays date.
The datetime in sql is for example 2015/05/09 12:00:00 and the current date is 2015/05/09. I want to compare these things if they are equal, but for the whole day so the time is a problem. I have the following query.
$q1="SELECT reservations.reservation_id, reservations.room_id, room.room_rate, reservations.arrival_date, reservations.departure_date,
meals.meal_rate, room.room_rate, roomtype.max_persons,
CONCAT(clients.first_name,' ',clients.last_name)as name
FROM reservations, clients, meals, room, roomtype
WHERE reservations.room_id=room.room_id AND reservations.client_id=clients.client_id AND room.roomtype_id=roomtype.roomtype_id
AND reservations.meals=meals.meal_id AND reservations.arrival_date=CURDATE()
GROUP BY reservation_id
";
reservations.arrival_date=CURDATE() this is equal only at 12:00:00 o'clock. i want that to be equal for the whole day.Actually i want to compare if these two dates are equal without time but my database must be datetime with the time...
does anyone has an idea?
thanx in advance
You should learn to use standard join syntax. Simple rule: Never use commas in the from clause.
The answer to your question is either the date() function (or something similar):
where date(reservations.arrival_date) = CURDATE()
Or an inequality:
where (reservations.arrival_date >= CURDATE() and
reservations.arrival_date < date_add(CURDATE(), interval 1 day)
)
The second is actually preferred because it can make use of an index on reservations(arrival_date).

How to filter MySQL dates?

I'm trying to do a SELECT * FROM but only items that are less than 30 days old. Here is my select code:
SELECT * FROM `{$table_name33}` WHERE `type`='wpst-requiredinfo' ORDER BY `foreignkey` ASC;
However, my problem is that I can't figure out how to add WHERE AND last_updated is less than 30 days.
I'm not exactly sure how to write the query, but the date is showing up like this: 1428412603 in the table column, it doesn't look much like a date to me. I don't know where to start.
Try this where clause:
WHERE `type`='wpst-requiredinfo' and
last_updated >= date_sub(now(), interval 30 day)
EDIT:
Your date seems to be in Unix time format.
WHERE `type`='wpst-requiredinfo' and
last_updated >= unixtime_timestamp() - 30*24*60*60
Note: this puts all the functions on the current time. In particular, it does not use FROM_UNIXTIME(last_updated). This ensures that an index can be used for this part of the query. The best index would be on (type, last_updated).

Proper MYSQL syntax for timestamp comparison and distinct results with certain exclusions

Sorry for asking, but I've never had to do such a complex MYSQL query before and I don't actually know what to google search in order to get the answer.
I have a poorly crafted database with a table of appointments of pregnant women that includes the day they came and the number of weeks pregnant they were at that time. I'm trying to select each one that should be 30 weeks right now but that doesn't already have a separate entry after 25 weeks pregnancy. I use the phone number to uniquely identify each person.
Since I really don't know how to formulate this query, this is the best I've come up with.
SELECT * FROM patientlist WHERE
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`) - `weekspreg`*604800) > 29*604800
AND
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`)- `weekspreg`*604800) <= 30*604800
AND
/* a subquery that keeps out results where the phone number would show up elsewhere in the table for a woman with more than 25 weeks of pregnancy. */
There has to be a better solution than separately querying each of the results from the date range by phone number to see if the weekspreg is more than 25.
Thank you in advance for any help or direction.
Your entire WHERE is incorrect. A query can only have ONE where clause. You join multiple conditions with and and or, not and where:
WHERE foo AND bar // correct
WHERE foo AND WHERE bar // syntax error
Check out the MySQL Date and Time Functions. For example, I'm not entirely certain what that last WHERE clause is trying to do, but I believe the first portion could be rewritten as something like:
SELECT *
FROM patientlist
WHERE `date` - interval `weekspreg` week
between now() - interval 29 week
and now() - interval 30 week

MySQL DATETIME question

I have a DATETIME field. I would like to select all the records that have been updated in the last week. Right now I'm using this query:
SELECT SUM(mins_spent) as time_sum FROM todos WHERE
lastUpdate >= '2008-12-22' AND lastUpdate <='2008-12-28'
But the results i get seem to be different depending on time of the day, e.g on 7 PM I might get 17 hours and on 11 PM I'l get 14 hours even though it should be increasing, not decreasing. I was thinking of changing the query to:
SELECT SUM(mins_spent) as time_sum FROM todos WHERE
lastUpdate >= '2008-12-22 00:00:00' AND lastUpdate <='2008-12-28 00:00:00'
Would it help at all? Suggestions please..
'2008-12-22' should equal '2008-12-22 00:00:00'.
Are you wanting "till end-of-day 28th?" If so, add 23:59:59 to the 2nd date.
Alternatively, you can use lastUpdate < "2008-12-29".
How are you tracking changes to an existing ToDo? INSERT and/or DELETE? Or UPDATE?
If you're DELETE'ing records upon "completion," you'll just have fewer records.
If you're UPDATE'ing, are you allowing dates to change to beyond the current week? If so, they'll be removed from your results.
To see what's happening, You may try grabbing a few aggregates on the table, mins_spent, and lastUpdate (mark down the values and run occasionally to see how they change).
SELECT count(*) AS Total
FROM todos
WHERE lastUpdate >= '2008-12-22' AND lastUpdate <= '2008-12-28 23:59:59'
SELECT min(mins_spent) AS Min, max(mins_spent) AS Max, avg(mins_spent) AS Avg
FROM todos
WHERE lastUpdate >= '2008-12-22' AND lastUpdate <= '2008-12-28 23:59:59'
SELECT min(lastUpdate) AS Min, max(lastUpdate) AS Max
FROM todos
WHERE lastUpdate >= '2008-12-22' AND lastUpdate <= '2008-12-28 23:59:59'
Judging from the MySQL 6.0 Reference Manual for Date and Time Types, you should be more or less OK as written. However, if it really isn't working, then you may have found a reportable bug.
A DATE value is coerced to the DATETIME type by adding the time portion as '00:00:00'. To perform the comparison by ignoring the time part of the DATETIME value instead, use the CAST() function to perform the comparison in the following way:
date_col = CAST(NOW() as DATE);
Your queries say '<= '2008-12-28'; that should be strictly less-than, not less-than-or-equal.
One very fine point would be: do the expressions you wrote get treated as DATETIME (because the LHS is a DATETIME column) or as a DATE (because the RHS is best treated as a DATE) or, indeed, does the DATETIME get converted to a string to match the RHS? It would make a difference if the LHS is converted to a DATE, because any time on the 28th would come in range, whereas you seem to want everything from the 21st to the 27th. What happens if you do explicitly fixup the types with casts?
Also, is the MySQL server running in the same time zone as you? There seemed to be an 'off-by-an-hour' difference between what you were seeing and the nominal end of day? I'm still not sure exactly how that might be (mis-)working, but it could be an otherwise unaccounted for factor.

Categories