MySQL select all dates between two dates - php

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)

Related

Best way to run a SQL query for different dates

I have a PHP application that records the sessions of various devices connected to a server. The database has a table session, with the columns device_id, start_date, end_date. To know the number of devices connected on a given date, I can use the request :
SELECT COUNT(DISTINCT device_id)
FROM session
WHERE :date >= start_date AND (:date <= end_date OR end_date IS NULL)
where :date is passed as a parameter to the prepared statement.
This works fine, but if I want to know the number of devices for every days of the year, that makes 365 queries to run, and I'm afraid things could get very slow. It doesn't feel right to be iterating on the date in PHP, it seems to me that there should be a more optimal way to do this, with a single query to the database.
Is it possible do this with a single query?
Would it actually be faster than to iterate on the date in PHP an running multiple queries?
EDIT to answer the comments :
I do want the number for each separate day (to draw a graph for example), not just the sum
the datatype is DATE
If I understand correctly then you first need a table of dates, something like:
create table dates(dt date);
insert into dates(dt) values
('2001-01-01'),
('2001-01-02'),
...
('2100-12-31')
And use a query like so:
select dates.dt, count(session.device_id)
from dates
join session on start_date <= dates.dt and (dates.dt <= end_date or end_date is null)
-- change to left join to include zero counts
where dates.dt >= :date1 and dates.dt <= :date2
group by dates.dt
PS: since you mentioned charts I might add that it is possible to avoid the table of dates. However, the result will only contain dates on which the count of devices changed. Chart APIs usually accept this kind of data but still create data points for all dates in between.

Get all rows from a specific month and year

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.

how to show one record per day order by id?

I have this little script that shows one wisdom each day.
so I have three columns.
Id wisdom timestamp
1 wisdon 1 4/1/2012
2 wisdon 2 4/1/2012
3 wisdon 3 4/2/2012
and I want to fetch array of one wisdom for each day
I looked around your website, but unfortunately I didn't find something similar to what I want.
also I got this code
$sql = mysql_query("SELECT DISTINCT id FROM day_table group by timestamp");
but this also not working.
any ideas?
is it possible to make a counter of 24 hours update wisdom date?
please give me some help.
You can make another table that is called wisdom_of_day
The table would have the following columns, id, wisdom_id, date
Basically each day you can randomly select a wisdom from your wisdom table and insert it into the wisdom day table. You can also add a constraint to your date column so it is distinct. It is important that it is a date column and not a timestamp since you don't care about time.
Then you can retrieve the wisdom of the day by querying based on the date.
It's possible I read your question wrong and you just want to select one wisdom for each day, but you want to show multiple days and you want to get the data from your table.
If so, the reason your query is not working is because you are grouping by a timestamp which includes the date and time. You need to group it by date for it to group like you want.
Here is a query that will group by the day correctly. This will only work if you have a timestamp field and are not storing a unix timstamp on an int column.
select id, wisdom, date(timestamp) date_only from day_table group by date_only order by date_only asc;
Hmm, I noticed that your timestamp values are in some kind of date format, maybe as a string? If so the above query probably won't work.
First compute number of days since 1970
SELECT DATEDIFF(CURDATE(), '1970-01-01')
Then insert this number inside RAND, for example:
SELECT * FROM table ORDER BY RAND(15767) LIMIT 1;
Rand with number as argument is deterministic.
Full query:
SELECT * FROM table ORDER BY RAND((SELECT DATEDIFF(CURDATE(), '1970-01-01'))) LIMIT 1;

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.

Group and manipulate based on multiple columns

I have a table that inserts a row when a certain function is used on the site and stamps the date.
code-/----date----/--type
-----/------------/------
--1--/--2012-2-1--/-used
--1--/--2012-2-3--/-saved
--1--/--2012-1-3--/-printed
--2--/--2012-2-1--/-used
--2--/--2012-2-2--/-printed
I have to report the number of times code 1 was (printed or saved or used) today, or yesterday, or last month (date range)
I am starting with this:
$stat_query = mysql_query("SELECT code, type, date FROM tracking WHERE code IN ('$htL','$htG','$htR') GROUP BY code, type, date");
I use the IN operand because each user has 3 codes to track with limitless date entries for each type.
I really am lost as to what to do here.
You'll need to construct the date ranges and modify the query. Below is an example of showing the count for code in the past day:
SELECT `code`, COUNT(`code`) as code_cnt
FROM tracking
WHERE
`code` IN ('$htL','$htG','$htR') AND
`date` BETWEEN DATE_SUB(now(), INTERVAL 1 HOUR) AND now()
GROUP BY `code`
Check out the DATE_SUB documentation for further help
GROUP BY code, type, date in this example makes it to return only one record. Because all code rows would be summerized in distinct output row, also type would be reduce more and more. Please check your GROUP BY fields.

Categories