Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Selecting A Entry Within A Date Range


I have a MySQL database with 5 columns called Name, Model, Colour, Date_From, Date_To.
Basically I want the user to specify the name and a date and want it to return the corresponding entry whose matches the name and within Date_From and Date_To.

I wanted to use the date format dd-mm-yy so ive used VARCHAR. This is what ive done of which the date range doesnt work.

SELECT Name, Model, Colour, Date, Date_From, Date_To FROM Cars WHERE Name='$Name' AND '$Date BETWEEN Date_To AND Date_From'




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Selecting A Date Range Using CURDATE()
When a user selects a page with the recordset I want it to list dates that
fall into a certain range, related to CURDATE(). The range fields are
start_date and end_date, which are both DATETIME column types.

Using BETWEEN won't work because it won't list a date that starts BEFORE
CURDATE() e.g.

If CURDATE() is 2005-08-10

Then an event that has a start_date of 2005-08-06 and an end_date of
2005-08-26 won't show in the list, even though the date range does fall into
the CURDATE() of 2005-08-10.

Selecting The Latest Date Entry
Basically I have a table containing these 4 fields
selection_ID - user_ID - visit_date (date field) - period_of_day

All I want to do is select one row - the one with the most recent visit_date for a particular user_ID.

I am using mySql 4.0.22 (so NESTED SELECT doesn't work).

I understand that there is a MAX function for getting the latest date but this seems to require GROUP BY, and I don't require a group of results.

I have vainly been trying things like this:

SELECT selection_ID, user_ID, visit_date, period_of_day FROM visits WHERE visit_date = visits.MAX(visit_date)

Selecting A Range Across A Range Of Fields
I am trying to gather stats from various categories. Each "item" can fit in as many as 8 categories and I have 25 categories to get stats on, which each have a unique numeric ID.

What I am using now is VERY processor intensive, so I am wondering if there is some way I can put everything into the SQL statement instead of running it through a loop as shown below:

$category_stats = array();
foreach ($categories as $k=>$v) {
$query_result = mysql_query('SELECT SUM(stats) FROM items_table WHERE '.$v.' IN(catid0,catid1,catid2,catid3,catid4,catid5,catid6,catid7)');

$result = array();
$result = mysql_fetch_row($query_result);

mysql_free_result($query_result);

$category_stats[$k]['stats'] = $result[0];
}

The $categories variable is just an array of 25 numbers, each corresponding to a category's unique ID. The stats field is an integer that is incremented on each stat increase.

Selecting A Range Of +10 And -10
I have a USPS zip code table that shows zip, city, state, latitude, and longitude.  I hope to allow a person to enter a zip code to find other locations near them.  While I can play around with formulas of latitude and longitude for proximity searches, I want to keep things simple by searching a range of zip codes (which are typically adjacent).

If I am searching for 10 zipcodes on either side of '64430', I could do...

SELECT *
FROM zipcodes
WHERE zipcodes.zip >= 64420
AND zipcodes.zip <= 64440;

Selecting Last Entry
All I need some help i have been trying to write this program for a friend that owns a internet cafe. The DB he uses is in sql he wants people to be able to see their time on his website i almost have it all written except for one problem when it selects there time it brings up all the changes to their account as in if he bought a hour yesterday it would so it i want it to show the current or last entry in the columns heres the code

SELECT userid, username, usertime, datetime
FROM users a, log b
where username = 'Their UserName'
order by datetime;

Is there any command so it shows only the last entry?

Selecting Range Of Numbers.
how to select a table of natural numbers in a given range. Is is possible to do something like this:
select list(0, 3);

to obtain:

+------------+
| list(0, 3) |
+------------+
| 0 |
| 1 |
| 2 |
+------------+

or something similar?

Selecting A Random Entry.
Is there any way to select a random entry?

to fit in with this statement...

SELECT * FROM `table` WHERE `type` = '1' LIMIT 1

Latest Date Entry + Future Date
My requirement is data to be added to database depending on dates. Like If the user wants to add data for the next 10 days,the data should be added with a corresponding column containing the next 10 days' dates.

Then if he logs in tomorrow and wishes to add data for another 100 days,it should find the last date added and then add data with the next 100 dates starting from that date.

Also I would want to display these dates to the user.So can you suggest which type to be used for database field and also the date functions(mysql as well as php) to be achieved.

Let me put it more clearly.

"select the last date(which might be future dates) entered in the database";

If the date is Oct10 and the user wants to add entries for Oct 11,12 13

"insert into table values('data','oct11')"
......
......
likewise for Oct12 and 13

The format I need is just year,month and day.No time is required.

Date Range Without Date Column
Suppose I have a table that says on which days I should eat certain foods:

+----+-------------+-----+-----+-----+-----+-----+-----+-----+-----+
| Id | Name | Qty | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
+----+-------------+-----+-----+-----+-----+-----+-----+-----+-----+
| 1 | Carrots | 3 | T | T | T | T | T | T | T |
| 2 | Cauliflower | 1 | T | T | T | T | T | T | T |
| 3 | Broccoli | 2 | T | T | T | T | T | T | T |
| 4 | Peas | 10 | F | F | F | F | F | T | T |
| 5 | Potatoes | 1 | T | T | T | F | F | F | F |
+----+-------------+-----+-----+-----+-----+-----+-----+-----+-----+
And suppose this is the calendar:

August 2006
MonTueWedThuFriSatSun
123456
78910111213
14151617181920
21222324252627
28293031
For the days August 8 through August 10 inclusive, how can I figure out how much food I should eat with an SQL statement?

The answer should be:
9 carrots
3 cauliflowers
6 broccoli
2 potatoes

Date Range From A Single Date
I have a football fixtures table with a date of the fixture stored with the fixture.
I want to display this fixture on my website for (say) 3 days before the actual fixture date and (say) 3 days after the actual fixture date.

Is this possible from within a single query? I think this might have something to do with the DATEADD/DATESUB functions, but I can't work out how to use these in the WHERE clause of my query.

Date Range On Date Field
I have a table that has birthday dates stored as a DATE field. How would I get all the rows returned based on a min years old and a max years old...Let's say...
My form has....

Display Rows by birthdate in years....

Show between (23 years old) AND (36 years old) from the current month/day/year

Not Between Date Range
I'm working on a booking system that allows users to search for properties that are available on a certain date.

For instance, if the user were to search for properties between 2007-02-15 and 2007-02-22...

+----------------------+
| name | date |
+----------------------+
| Property1 | 20070221 |
| Property1 | 20070220 |
| Property1 | 20070219 |
| Property2 | 20070214 |
| Property2 | 20070213 |
| Property2 | 20070212 |
| Property3 | 20070216 |
| Property3 | 20070215 |
| Property3 | 20070214 |
+----------------------+
Only Property2 would be displayed because Property1 is booked from the 19-21st and property 3 is booked from the 14-16th.

I had a look through the manual and found NOT BETWEEN which seems ideal on paper, but it's including Property3 because that's available on the 14th, despite also being booked on the 15th and 16th.

A regular BETWEEN command returns the expected results though, showing Property1 and Property3 as booked. But what I need is the inverse of that (ONLY properties that aren't booked from the 15-22nd), and it's proving pretty tricky!

Here's the command I've been using:

SELECT DISTINCT name, date FROM properties, pdates WHERE PID=ID AND date NOT BETWEEN 20070215 AND 20070222;
As you can see I've two different tables here: properties and pdates which are tied together using ID/PID. There's an entry for each date booked in pdates, so each date range comprises of three rows.

Hope all this makes sense, any help would be much appreciated as I'm really stumped here!

EDIT: I'm using MySQL 5.1 on an Apache server. The date column is a varchar type.

Date Range
I want to restore the backups made in MySQL within a specfied date range. For eg I had taken backup between the dates 01/01/08 to 01/02/08. Now i want to restore it by specifying the date range as 10/01/08 to 20/01/08.

Date Range
[MySQL] Having unsuccessful attempts at returing records that fall within a given date range...

Given two fields of either DATE or DATETIME types: {startEvent, endEvent} = {2/7/2005, 2/7/2005}

SQL:
SELECT * FROM table WHERE startDate <= '2/7/2005' AND endDate >= '2/7/2005' ORDER BY eventID

This returns nothing.  I can just do a startdate > '2/7/2005' and that returns the record - but obviously not what we're trying to do here.

This does work w/ MS Access though:

SELECT * FROM table WHERE startDate <= #2/7/2005# AND endDate >= #2/7/2005# ORDER BY eventID

Date Range
There is probably an easy way to do this, but for the life of me I cant get it to work no matter what I try.I need to select data between two dates a table - this bit I can achieve no problem. However, my query is not that simple - the date rangeI need to select is always going to be between the current date and 7 days forward, i.e I want to select all data between and including the current date and 7 additional days.I presume I use the CURDATE() function to generate the current date, but how do I work out CURDATE + 7 days and then get the query to select all the data between and including those two dates?

SQL For Specifying Date Range Please
I have a table that has a date field in it, in the format of yyyy-mm-dd In my sql I want to select all records who have a date greater than (>) the current day (today). I tried this but to now avail

sql = "select * from specials where exp > 2006-06-28

and this

sql = "select * from specials where exp > '2006-06-28'

I am using asp for this and here is my table structure:


CREATE TABLE `specials` (
`id` int(10) NOT NULL auto_increment,
`title` varchar(100) NOT NULL default '',
`special` text character set ascii NOT NULL,
`exp` date NOT NULL default '0000-00-00',
`price` double NOT NULL default '0',
`image` varchar(50) NOT NULL default '',
`shop` int(4) NOT NULL default '0',
PRIMARY KEY (`id`)
)

Date Range
I have a database where the date is stored in 3 different collums month, day, year. A am trying to retrieve data by a date range something like "1-1-2005" - "1-1-2007" or something but had quite some difficulty in doing it but I found a way and I am not sure that it is the best way but it appears to work well. Let me know what you think.

Code:

"SELECT * FROM database " +
"WHERE datey*365+DAYOFYEAR(CONCAT(datey, '-', datem, '-', dated)) " +
"BETWEEN " + StartDate + " AND " +
"EndDate + " " +
"ORDER BY datey, datem, dated;"


NOTE: StartDate and EndDate use the same formula of (year*365)+dayofyear

Date Range
This is somthing i've not worked with before so thought i'd come on here for a little help.
I have a database with a whole stack of records, one for each day which is generated by a script on the server.
I am giving my users the ability to choose a startDate and endDate for thier report to be built, i then want it to take all records from the database between those dates and Add the values of all the returned rows together and pass them as a single row back to me.
Is this somthing that can be achieved in MySQL? or will i have to just run a standard query to return the results and then have my SeverSide scripts so the math?

Date Range
I'm constructing a dynamic search page that will search for available facilities based on criteria entered. If the "reservable" box is checked, a set of date range fields will appear so that the user may see what facilities are available for a specific date range.My "event" table holds all reservations and events and so my query should check for a date range NOT in the event table, in order to see what is available. If it is not in the event table, then it is available to be reserved and should be returned in the search results.Syntactically, is there a way to do this or do I need to try using some sort of sub-query? Using (!BETWEEN) doesn't work and I can't find anything else regarding a date range that you DON'T want to view

SQL Date Range Query
I need some help with this one. I hate admitting defeat but I'm getting frustrated!

I've got a table called 'Events' with these fields...

eID
eName
eStartDate
eEndDate

An example entry would be...

1
'Course Open Day'
12-Nov-2006
14-Nov-2006

What I want to be able to do is search the table and select any records where a given date falls between the the startDate and endDate.

So, if I searched with &#3913;-Nov-2006' i'd get 'Course Open Day'.


Datetime &amp; Date Range
MySQL version is 5.0.24 and database engine is MyISAM, the field "algus" in table ajad has the type "datetime".

And here is my problem:

Select Date Range
I need a SELECT query that will select records from the past 12 weeks and one that will SELECT records from the past 12 months. the 'compdate' field is a DATETIME field. I have gotten it so far to select records from the same month, and the same year.

All form current week: "SELECT * FROM table2 WHERE MONTH(compdate)=$month AND WEEK(compdate,1)=$week ORDER BY id DESC"

All from current month: "SELECT * FROM table2 WHERE MONTH(compdate)=$month AND WEEK(compdate,1)=$week ORDER BY id DESC"

$month is date("m") in php
$week is date("W") in php

Date Range Request
Dates are stored in unix format GMT. I want to find all records either by "day" or by A Date Range "week" i have to deal with users seeing data in their time zone so people in GMT +9 would see records posted accordingly to someone in say GMT -8? Code:

Date Range Logic
I attempting to  returing records that fall within a given date range and any overlapping dates:

For example:
input parameters are:
startDate= 2005-10-31
endDate = 2005-11-30

If I have the following data in my table:

cust dateBeg     dateEnd
------------------------
1    2005-10-27  2005-11-15
2    2005-11-1   2005-11-30
3    2005-11-20  2005-12-20
4    2005-12-1   2005-12-10

I want to retrieve cust 1,2,3, but not 4
So far this logic retrieve all dates that fall in between

(dateBeg >= startDate and
dateEnd <= endDate)

How can I include ovelapping dates?

Sum Of Groups Within Date Range
I have the standard orders table, with the amount of an order, the order id, the customer id, and the date.  What I now need is the ability to group the order totals by quarter.  So give customer id, I need to be able to display how much they spent between each quarter.

Is this possible without running the same sql for each quarter?

Date Range Sorting
how to return data by date ranges, where I return all
data made:

Today,
(Every individual day of the week up to 1 week ago - eg. Everything for
last Monday, last Tuesday etc)
Two/Three weeks ago
Anything over three weeks ago

Also, is this something best done in PHP after a full query or during
SQL?

Date Range MySQL
show me the code where I can return all recoreds whose date field is greater than today but less than 3 months from today.

Query Date Range
I have a Date/Time field that has a date and time as the data in the field, in a table that I want to run a query on returning records that are in a date range.

What would the select statement be to return the records in the date range just by date so any record in that date range will be returned regaurdless of its time?

Invoice With Date Range
Am I able to allow user to choose to list the invoice from selected date to selected date as a date range by using mysql? How?

Qucertain Date Range
this is apart of a PHP thing im doing. the script will be given a string such as "Decemeber 2006" and I want to use it to search through a table and select rows where the DateCreated column(which datatype is "Date") is a date in the month of decemeber in 2006

of course you can't just put in December 2006 into the query (right?). so I guess I'll need to use PHP to manipulate the string into something usable in a query, thats not really an issue, it's just some simple string parsing and such.
I just don't know what I should be parsing the string to. bassicaly i need to know whats the best way to do this query so i'll know how to reformat the string for mysql.

Auto Date Entry
Is there a way to have a date automatically entered into a form, so the user does not always have to add it manually? What table Type do I use? I see a TIMESTAMP, but no DATESTAMP.

Select Not Matching Date Range
I'm looking to write a query which returns a date range result that does not match any date range in the database.

Example.

id date_from date_to
1 2007-10-10 2007-10-11
2 2007-10-12 2007-10-13

Query returns 2007-10-11 or something along those lines.

Is it possible at all?

Help With SELECT Statement For Date Range
I have a table that has an event StartDate and EndDate, based on the current Date "NOW()" I need to know which records are currently active. Can anyone help with a quick SELECT statement?

SELECT Statement For Date Range
I have a table that has an event StartDate and EndDate, based on the current Date "NOW()" I need to know which records are currently active. Can anyone help with a quick SELECT statement?

Need To Check If Date Falls In Range
i have two fields in a booking table, one called arrival date and the other called departure date. I need to check if a user inputted date falls within those two fields ranges. Code:

Slecting Records Within A Date Range...
I need to perform a query on a small table (bookings). The table has 2 fields that include the booked from and to dates. I'd like to be able to run a query to see if an individual date is 'taken'.

The format of the 2 fields is YYYY-MM-DD, the date passed to the query is currently formatted identically, but could easily be changed if need be.

I've tried many other work-arounds but am very frustrated now.
Basically, I'd like a true if 2008-10-22 is given (assuming that there is a book_from of 2008-10-19 and a book_to of 2008-10-26).

SELECT Statement For Date Range
I have a table that has an event StartDate and
EndDate, based on the current Date "NOW()" I need to
know which records are currently active. Can anyone
help with a quick SELECT statement?

Compare Date Range In A Table
how to select data from a table that is based on the comparison of the date in the table to today. For example, I want to do the following:

SELECT * FROM tablename WHERE 'date' >= 'now' AND coldate <= 'now + 6 days'

How do I write that query? The date format in the table is yyyy-mm-dd.

Calculating A % Based On Date Range
I have a table called TransResult and I have 2 data fields in it. I want to get the percentages for the 2 possiable values in TransResult and I want this done by date, so I can go backwards to compare what was done in the past months to what is done in current month.

This is what i have come up with so far, however my _total is giving me ALL records in the table not this months records, so my percentages are off, aside from the _total the values it is calculating are correct.

SELECT TransResult, COUNT(*) AS HowMany, (COUNT(*) / _total ) * 100 AS Percent FROM tbltranslog, (SELECT COUNT(*) AS _total FROM tbltranslog) AS myTotal WHERE MONTH(Date) = MONTH(NOW()) +0 GROUP BY transresult

Date Type Column Range
I'm using a date type column for Date of Birth. The problem is that it seems that the Year range starts 1970!! is it true? How can i fix this problem?

To Find Days Per Month In A Date Range
How to find days per month in a date range using MySQL query?

For example I have a start date - 04/28/2007 (mm/dd/Y) and end date 05/04/2007 , I have to find the days in each month that comes in the above date range

In the above example the days in April are 3 and in may the days are 5

(I am using MySQL database,Please find a query that outputs the above result)

Counting Values That First Occur During A Date Range
I don't know why the query for this is eluding me.. I haven't had a problem coming up with a query for something in a while.

I've got a table with two relevant columns, a name and a datetime created_at. The name can occur on many rows at various times.

I am creating a list of all names whose first entry into the table was during a user-specified time frame. I have that working fine. It looks similar to this:

SELECT name, MIN(created_at) as `min_time` FROM table GROUP BY name HAVING `min_time` BETWEEN ? AND ?
In order to page this list, to display only 20 rows at a time, I need to also count how many names appeared during the time frame. For some reason I can't think of the COUNT() to do that...

Finding Column Total In Specified Date Range
I'm stumped on an issue that I'm hoping someone can shed some light on.

I have a table that tracks financial transactions for multiple members with two key fields being 'available' and 'pending' balances. I am trying to write a select query that will allow me to view the total available and pending balances for all members in a specified date range.

Essentially what I need to do is select the sum of each balance type from each unique member at the latest point in the given date range.

I've been toying with queries like:

SELECT id, MAX(available_balance) AS available, MAX(pending_balance) AS pending FROM members.trans_hist WHERE date BETWEEN '$fromDate' AND '$toDate' GROUP BY pt_id"

Generate Multi-results From Date Range
I am running MySQL 5.0.15. I am not an SQL expert. I have the following situation: I have a simple table that holds brief info on some actions that we expect to happen.

actions (
id INT unsigned PRIMARY,
name varchar(128) not null,
start datetime not null,
end datetime not null,
)

A record could have time values that both happen on the same day or span one or more day boundaries. We are not creating a "calendar" but the display interface of a monthly calendar view is useful. If I have the data: Code:

Grouping Entries By Entry Date And Parent ID
With tables:

'Category' comprised of (and containing e.g.)
----------------------------------
categoryId | title | description
----------------------------------
1 | Animals | Different kinds of animals.
2 | Cars | I love cars.

and
'Subject' comprised of (and containing e.g.)
-----------------------------------------------
subjectId | categoryId | title | description
-----------------------------------------------
1 | 1 | Welfare | Something about animal welfare.
2 | 2 | Engine | Something about the engines of cars.

and
'Issue' comprised of (and containing e.g.)
-------------------------------------------------------------------
issueId | subjectId | parentId | status | entryDate | text
-------------------------------------------------------------------
1 | 1 | 1 | Not done | 2007-01-12 10:00 | Feed my dog.
2 | 1 | 1 | Done | 2007-01-12 10:05 | Feed my dog Alex.
3 | 1 | 3 | Done | 2007-01-13 11:00 | Feed my cat.
4 | 2 | 4 | Done | 2007-01-14 12:00 | Get new engine.


I would like to do a SELECT which will join these three tables, and give me the following result.
-------------------------------------------------------------
catTitle | subjTitle | issueText | status | entryDate
-------------------------------------------------------------
Animals | Welfare | Feed my dog Alex. | Done | 2007-01-12 10:05
Animals | Welfare | Feed my cat. | Done | 2007-01-13 11:00
Cars | Engine | Get new engine. | Done | 2007-01-14 12:00

Note how the newest entry of issues with the same parentId overwrites the ealier entries with the same parentId.
This is because I would like to keep some log of what has happened in the database, when I for example updates the dog-feeding situation from "not done" to "done".

What does my SELECT look like to accomplish this?

NB: Copy/paste this into a word editor and use a monospace font for optimal rendition.

MYSQL Date Entry Shows 0000-00-00
i want the user to type in the date. Everything works fine and the form submits. When i open the database and query the results, the date field shows only 0000-00-00. It doesn't show the date entered (ex 05/23/07). What am i doing wrong?

I'm thinking it has to do something with converting the string to a date? If so, how do i do that in PHP.

Adding User Defined Date Range For Report
Hello I have a very simple query that list customer info within a date range. I would like to have a interactive form that would allow the customer to choose between two dates and query the DB for information between the two dates entered. it is coded like (WHERE `date_purchased` > '2005-08-01 00:00:00' AND `date_purchased` < '2005-09-01 00:00:00') below is the code but I need help or guidence on how to get the customer input into the query instead of the hard coded area that is there now....

Viewing Date Range Then Adding Column Totals?
this is probably my most complex question to date. Basically i have a table that stores order information for products. What i need to do is:

- Specify a Date range
- Count number of rows in that range
- Get column totals for that range
- Return Array with column totals eg, if the array was named $total, $total['column1'] would be the column 1 total :)

This is a large table with many columns so here is what i had planned:

//OPEN CONNECTION HERE, SET DB
//First query gets date range:
$result = mysql_query("SELECT * FROM D_Orders_Columbus WHERE odate > '" . $startdate . "' AND odate < '" . $enddate . "'");
//now we get number of rows:
$num_orders = mysql_num_rows($result);

After that i get stuck, i need it to ADD the column values together, for this i assume i will need to set the column types to 'SMALLINT' (i dont assume anyone will order 32000 items :p). How can i get mysql to total all the columns that can be (eg. have number types) and then return an array with the totals?

Search MYSQL Date-range With Unix Timestamp?
I want to search for records that are ON or After a certain date in a column that uses MYSQL date form (yyyy-mm-dd) with a unix timestamp. Can this be done?


Copyright © 2005-08 www.BigResource.com, All rights reserved