Get all rows from a specific month and year - php

I have a PHP scirpt that is always querying all the data from a database table and it's getting pretty slow. I really just need the data of a specific month and year.
Is there a simple way to get only those entries? For example, everything from February 2013?
The column that stores the dates in my table is of type datetime, if that applies to the solution.

You can add that condition in the WHERE clause of your select statement. I would recommend using BETWEEN operand for two dates:
SELECT myColumns
FROM myTable
WHERE dateColumn BETWEEN '2013-02-01' AND '2013-02-28';
If you mean to say you want everything beginning with February 2013, you can do so using the greater than or equal to operator:
SELECT myColumns
FROM myTable
WHERE dateColumn >= '2013-02-01';
EDIT
While the above are my preferred methods, I would like to add for completeness that MySQL also offers functions for grabbing specific parts of a date. If you wanted to create a paramaterized query where you could pass in the month and year as integers (instead of a start and end date) you could adjust your query like this:
SELECT myColumns
FROM myTable
WHERE MONTH(dateColumn) = 2 AND YEAR(dateColumn) = 2013;
Here is a whole bunch of helpful date and time functions.

You should index the datetime field for added efficiency and then use Between syntax in your sql. This will allow the mysql engine to remove all records that you are not interested in from the returned data set.

Related

How to select data by using range of dates in MySql query?

I have a problem related to MySQL query, I use WAMPServer.
I have data in database which have range of dates but when I select data for example
select * from CHD WHERE addtime>='2018-06-15' and addtime<='2018-06-21';
It displays data from '2018-06-15' to '2018-06-20', data of 2018-06-21 are not displayed even if I do
select * from CHD where addtime='2018-06-21';
is not working
Please anyone can help me
This assumes that your column is of type datetime.
The shorthand version of your date in the filter clause is assumed to be at midnight of the date. Your values that you are attempting to retrieve have times after midnight of that date. You either need to define a timestamp along with the date, or you need to filter by the day after for less than equal to or the day before for greater than equal

How to select last 7 days results from mysql (with custom data field)?

I need to select data from mysql for last 7 days. I have field named 'date' and which have values in mm.dd.yy format.
So i tried to find special mysql request to do that, but its not work with my field, i gues that beacause date in wrong format.
How i can do that from php (use some variable to get mysql entries), or with custom select query ?
You can use STR_TO_DATE() to convert your idiosyncratic date format to a standard DATE value. An expression like this will do the trick
STR_TO_DATE('07.17.97', '%m.%d.%y')
Then you can say
WHERE STR_TO_DATE(`date`, '%m.%d.%y') >= CURDATE() - INTERVAL 7 DAY
in your query to filter items with date values starting a week ago.
But, if you have a lot of rows to filter you will have poor performance: this kind of WHERE clause is not sargable.
First read your table and change the date format
$new_date_format = date('Ymd',mktime(0,0,0,substr($date,0,2),substr($date,3,2),substr($date,6,2)));
After that you can make comparisions

MySQL comparing stored date with current date and execute

I have stored dates (dd/mm/yyyy) in text format in a table in a field called dates. I want to compare those dates with the current date and if the dates are smaller (if the dates have passed) to move the entire row into a new table called archive. Tried something with the DATEDIFF() but I'm new to MySQL and can't figure it out.
I'm going to preface my answer with a short remark: storing "date" values in SQL database in VARCHAR columns is an anti-pattern. MySQL provides native datatype DATE which is designed to handle "date" values. But that's just a remark, doesn't answer your question.
You can use the convenient MySQL STR_TO_DATE function to convert strings into DATE values. For example:
STR_TO_DATE('15/05/2015','%d/%m/%Y')
You could use a column reference in place of the literal, e.g.
STR_TO_DATE(t.mycharcol,'%d/%m/%Y')
and that will return a DATE value you can compare to another DATE value, using the standard inequality operator < for example.
To return the current date from the database, you can use an expression such as
DATE(NOW())
Putting that together, you could write a query like this:
SELECT t.*
FROM t
WHERE STR_TO_DATE(t.mycharcol,'%d/%m/%Y') < DATE(NOW())
If you want to take the result from a SELECT statement and insert those rows into another table, you can use the INSERT ... SELECT form of the INSERT statement.
Reference: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
Beware of the behavior with badly formatted or invalid dates, e.g.
SELECT STR_TO_DATE('35/05/2015','%d/%m/%Y')
, STR_TO_DATE('15-05-2015','%d/%m/%Y')

MySQL select all dates between two dates

I have a table called schedules which contains columns day, month, year, etc. What I need is to select records between the $datefrom and $dateto. Here is my code that does not work :(
SELECT * FROM schedules WHERE CONCAT(year, month, day) BETWEEN $datefrom AND $dateto
Im not sure if this is correct. Please help.
Like showdev already said in a comment, you have to cast the string that is returned from CONCAT() function to date. But consider, that no index can be used on this.
I'd suggest you create an additional column in your table with the full date. I don't know if you separated the date into 3 columns out of performance reasons, but have a try, if only one column is enough for you. Usually it's fast enough (when indexed).
If you don't want to do that and want to use indexes (if they exist at all on those 3 columns) you would have to write the query like this:
SELECT * FROM schedules WHERE
`year` BETWEEN YEAR($datefrom) AND YEAR($dateto)
AND `month` BETWEEN MONTH($datefrom) AND MONTH($dateto)
AND `day` BETWEEN DAY($datefrom) AND DAY($dateto)

SQL count stays per day query not working as expected

Let's assume I manage medical patient stays information system.
I want to get the patient count per day with the following minimal structure :
stay table has begin and end datetime columns
PHP gives me $first_day and $last_day limits
The following snippet is NOT what I want, since it only counts entries per day, and not present stays per day:
SELECT
DATE_FORMAT(`stay`.`begin`, '%Y-%m-%d') AS `date`,
COUNT(`stay`.`stay_id`) AS `total`
FROM `stay`
WHERE `stay`.`begin` <= '$first_day'
AND `stay`.`end` >= '$last_day'
GROUP BY `date`
ORDER BY `date`
Last but not least, I'm looking for a full SQL query.
It goes without saying that making one SQL query for each day would be totally trivial.
Use of temporary (dates ?) table is clearly an option.
As you mentioned using a temporary table of all dates in the range you want is one way to handle this. If you created a table of date called foo with all dates between $first_day and $last_day inclusive (see here).
Then you can write your query like:
SELECT f.date, count(s.stay_id)
FROM foo f
JOIN stay s ON s.begin <= f.date AND s.end >= date
GROUP BY f.date
ORDER BY f.date
A quick Google around leads me to this page: What is the most straightforward way to pad empty dates in sql results (on either mysql or perl end)?
What I would suggest is that you either follow the advice in that question, or construct your own loop in PHP.

Categories