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




Search Query By Date


I'm trying to adjust an older search query to perform a search by date where the date column is an INT field (unix date stamp).

SELECT * FROM incidents WHERE date < DATE_ADD (CURDATE(), INTERVAL $searchDate DAY);

Where date, formally a DATE field, is now an INT(11) field. $searchDate is an int, indicating how many days back to search. 1 (day), 5 (days), etc.I'm assuming mysql's DATE_ADD function is specific to the DATE field. How can I achieve the same result, but with an INT field?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Date Search Query Help
I'm trying to filter my search results by date. The field name I'm running this for is final_date and is a DATE field.

I want my results to show records that have sales_reps.final_date within the past 30 days.

Query:

SELECT
sales_reps.sr_id,
sales_reps.name,
sales_reps.job_number,
sales_reps.status,
sales_reps.stage,
UNIX_TIMESTAMP(sales_reps.final_date) as final_date,
UNIX_TIMESTAMP(sales_reps.date_to_shop) as date_to_shop,
shop_orders.community,
users.user_id,
u.fname,
u.lname,
users.builder,
users.division,
ei.shop_result,
ei.good_tape,
sa.shopper_id,
shop_orders.order_id,
UNIX_TIMESTAMP(shop_orders.date) as order_date,
pi.fname as pfname,
pi.lname as plname ,
ei.exit_id
FROM sales_reps
LEFT JOIN shop_orders ON sales_reps.order_id=shop_orders.order_id
LEFT JOIN users ON users.user_id=shop_orders.builder_id
LEFT JOIN report_types ON report_types.type_id=sales_reps.report_type
LEFT JOIN shop_assignments as sa ON sa.sr_id=sales_reps.sr_id
LEFT JOIN exit_interviews as ei ON ei.shop_id=sa.shop_id
LEFT JOIN users as u ON u.user_id=sa.shopper_id
LEFT JOIN users as pi ON pi.user_id=sa.pi_id
WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <=UNIX_TIMESTAMP(sales_reps.final_date)
AND (sales_reps.status = 'Completed' OR sales_reps.status = 'Rejected')
ORDER BY users.builder, users.division, community ASC, final_date ASC
Is this:

WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <=UNIX_TIMESTAMP(sales_reps.final_date)
incorrect?

I'm getting dates such as 2007-03-22 and 2007-03-19 in my result set and they shouldn't be there.

Could I get some pointers?

Search A Date Field
I have a date field defined as:

'created_date' timestamp NOT NULL default '0000-00-00 00:00:00'

It is also an indexed KEY. What would be the fastest search on that field if my desired results were for records created during a specific month?

created_date LIKE '2007-07%'

created_date REGEXP '^2007-07'

created_date>'2007-07-01 00:00:00' AND created_date<'2007-08-01 00:00:00'

Thanks for your opinions.

BTW, if you know Perl do you think it would be faster for MySQL to give me created _date data as DAY(created_date) or for Perl to split the date (first on a space character and again on the hyphen character)?

Fulltext Search Sort By Date?
How do you sort by a particular column (such as date) for fulltext search results? (example table:

id
url
category
blurb1
blurb2
date

Date Search Mysql Question
I use this query on the DB
"SELECT * FROM {$_TABLES['events']} WHERE datestart >= date_sub(current_date, interval 3 month) ORDER BY datestart

My Date entries in mysql:
2004-12-10

Now My problem is I keep on getting the past entries in there.
What is wrong with my query?

Search A Table For A Date With DateTime Variables
i have a table with two columns, id and DateTime (YYYY-MM-DD HH:MM:SS). I want to find all rows with a certain date (YYYY-MM-DD). how can i do this, is there a kind of wildcard that will allow any "time" when search for a DateTime?

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?

Search MYSQL Date Column 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.

Date Query (how Do I Get Everything With A Date In 7 Days?)
the goal is a reminder email to people who have a workshop coming up in 7 days.

So, workshop date is 2006-05-25.
The reminder email should go out on 2006-05-18

I guess mysql query returns all records where (Date column - 7 days) = current date. Right?

But what does teh QUERY look like? And how does it accomodate if today is 2006-05-28 and the upcoming workshop is 2006-06-04 (so month changes over the 7 day period).

Correct Search Query
Can anyone help me out with this please. I am looking at searching among comma delimited id's stored inside "IDs", trying to figure out what the correct SQL query for that would be. I need to extract the ID where IDs contains the value 7. I know I can't use something like "WHERE IDs LIKE '%7%'" because the result would be inaccurate. So how do I go about it, please? Any directions would be appreciated, thanks!

+------+-----------+
| ID | IDs |
+------+-----------+
| 1 | 3,17,20 |
+------+-----------+
| 2 | 1,7,9,12 |
+------+-----------+

Search Database Query
I am looking for a query that will search all of my database without having to use all the individual table names and fields as there are 6 tables and over 30 fields in the database is there any special expression for this the search criteria would only be one word.

Mysql Search Query
i would like to write a query to seach for the related information to display.

let say the user key in the word "sql", and in one of my keyword field i have data such as "mysql, database, java" and i want to call this row out, how can i do this?

Query Search Direction
It's possible to tell mysql to start searching rows from highers indexes to lowers?

MySQL Search Query
I have two tables as follows:

table 'question' with fields 'patient_id', 'answer_id' and 'terms', and

table 'answer' with fields 'answer_id' and 'answer_path'.

I need to search question.terms for a keyword match and then join that match to the corresponding foreign key (answer_id) in table answer to return 'answer_path'.

[PHP, MySQL, FLASH] - Search Query
just a quick question what would be the best way to search a database, how should i query it? i have this so far:

<?
$name=$_GET['name'];
$company=$_GET['company'];
$address=$_GET['address'];
$phone=$_GET['phone'];
$email=$_GET['email'];
$web=$_GET['web'];

mysql_pconnect("host","random","random") or die ("didn't connect to mysql");
mysql_select_db("database") or die ("no database");

$query = "SELECT * FROM table_name WHERE Name, Company = '$name' AND '$company'";
$result = mysql_query( $query ) or die ("didn't query");

$num = mysql_num_rows( $result );
//echo ($num);
if ($num == 1){
while ($line=mysql_fetch_array($result)) {
$profile = "name_show=" . $line['Name'];
$profile = "company_show=" . $line['Company'];
//$profile = "address_show=" . $line['Address'];
//$profile = "phone_show=" . $line['Phone'];
//$profile = "email_show=" . $line['Email'];
//$profile = "web_show=" . $line['Web'];

}
print $profile;
} else {
print "error=Sorry, but I can't show results";
}
?>

it works but not very dynamically, when both companys are commented out in the while and query statements.

What i hope to have is a search where users can type in 1 letter and it will give them a result with all records having that letter in them and just by filling in one item in flash instead of all of them in order to begin the search.

Incorporate OR Operator In Search Query
I have 2 tables, one with restaurants and one with US centroids, latitudes longitudes, zipcodes for varius central cities in the us.

I have a query that I got working, that uses these 2 tables, it selects all restaurant data from table Restaurants city/state/zip... where the restaurant zipcodes are within the dynamic radius specified of the zipcode(centroid) specified.

This works fine, It also returns the distance as well.

I would also like to select restaurants records regardless if the the distance between zipcodes only IF the Restaurant City matched the CIty I pass to the query. I tried adding an OR operator but my query hung.

Here is my query:

Query A Thesaurus For Search Terms?
I was wondering what the best way is to expand on user-inputted search terms.

For instance, when conducting a search, I would like to ALSO query all synonyms and related words to the inputted search terms.

The database my script searches is very large, so inputting my own related words and synonyms alongside every searched value in the database would be a real pain in the neck if I had to go that route.

Is there some sort of downloadable database of all words and their relations I could use?

Query Search In Different Table Columns
I'm trying to set up an sql-query to find a value in the table, which can exist in different columns......

Tire Size Search Query
I have a table of tire sizes... example: 245/40 YR18, 245/40 W18
I need to search through that table, and pick out sizes based on a search that would like like this: P245/40ZR18
I want to find tires based on the 'P245/40' and '18'... any combination of letters between the two are fine....
seems like a regular expression seach?

Query To Search Multiple Fields
I have a table with over 50 columns that contain yes/no values. I want to know if there is a way to write a query to get all fields that have a value of "no".

SQL Query Problems (for Use With A Sort Of Live Search)
I created some code that loaded information from an XML file, but many thanks to jimfraser on here I'm working on a solution that'll drag it directly from the database.

Problem is, it's not displaying anything at all, so I assume there's a problem with the SQL query or the way it's being presented on the page.
PHP
<?php
 
$network = new COM("WScript.Network");
include_once('../../../functions/datalib.php');
 
$db = new oracleClass();
$conn = $db->connect();
 
//get the q parameter from URL
$q=$_GET["q"];
 
//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
    $hint="";
 
    // connect to the database
    $sqlstatement = 'select * from TEST."WFO_REPORTS_ALLEMPS" order by "Surname", "Forenames"'
    $sqlListings = OCI_Parse($conn, $sqlstatement);
       
    OCI_Execute($sqlListings);
    while(OCI_Fetch($sqlListings)) {
   
        $name = oci_result($sqlListings, "Forenames") . ($sqlListings, "Surname")
 
        //find a link matching the search text
        if (strchr($name,$q))
        {
            if ($hint != "") {
                $hint .= "<br />";
            }
 
            $hint .= "<a href='#' onclick='employee_form.Line_Manager_Staff_No.value="
            . oci_result($sqlListings, "Gc_Staff_Number")
            . ";checknumber('Line_Manager_Staff_No','displayusername');'>"
            . oci_result($sqlListings, "Surname") . ", " . oci_result($sqlListings, "Forenames")
            . "</a>";
        }
    }
}
 
// Set output to "no suggestion" if no hint were found
if ($hint == "")
 {
 $response="No user found.";
 }
else
 {
 $response=$hint;
 }
 
//output the response
echo $response;
?>

On a side note, is there a way I can change it so that the search will present any users based on their first name, as well as the surname?


Optimizing Search Query For Millions Of Rows
I have mysql 4.1 and Im having a difficult time optimizing this query.

select domain, length(domain) as len
from domains
where
length(domain) <= &#3916;' and
not (domain regexp '[[:digit:]]') and
domain not like '%-%' and
price > &#390;' and price < &#3916;' and
end > &#55614;&#57159;-12-01'
order by end ASC, len ASC
The following query outputs:


| id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra |
-------------------------------------------------------------------------------------------------------------------------------------
| 1 | SIMPLE | domains | ALL | end | NULL | NULL | NULL | 2600000 | Extra where; Using filesort |
My indexes are:
ID - PRIMARY, Unique
domain - Unique
end

Is there anyway this query could be optimized anymore? With only 2.6 million rows its taking a 5 or 6 seconds. It looks like its not finding the right keys.

Mysql Query Search And Find In String
I have following values in a field of mysql table. These values are stored as string [varchar] in the field.

Values : 3,4,10,21,20,8,100,2,6

How can I check through MYSQL query that 100 or 21 or 4 exists in the string?



Query To Search And Retrieve File For Download
I am new to web development and have this challenge. I want to design a dynamic website for a college community using PHP and MYSQL. The objective of the site is to hold the annual report of all the departments such that visitors can select the desired department and the year of the report. The years could stretch back to as long as the college existed but I want to limit the backdate to 10 years for now. The visitor should be able to select a department and desired year, view the report online and also be able to download the same report stored in a directory in ms word or PDF format. What should the table structure look like? Also the PHP and SQL script to search for the stored files and make them available for download.

SELECT Search Query - Table Join Required? Help Please!! (PHP + MySQL)
I have a search form that has:
- drop down with states (nsw, vic etc)
- drop down with all business categories (retail, commercial etc)
- keyword / postcode field (2000, or 'builders')

The user gets results returned from the business table filtered by state (mandatory), which category is selected (mandatory) and by keyword (optional) or postcode (optional).

If keyword / search phrase is given then it will do search of the keywords fields of the business table (has already been indexed) in the selected category only. If postcode it will return all businesses in that category in order of distance from the given postcode.

I have 5 tables (additional fields ommitted):

'state'
state_id, name

'businesses'
business_id, keywords, name, postcode, state

'postcodes'
fromPostcode, toPostcode, distanceKMS

'categories'
category_id, name

'business2category'
business_id, category_id

Please dont thing i'm just pawning off my work here!!
Basically, i've got this working already, but only just, and in a very long and convulted format. Its far too long to post here, but since i'm not fully versed in table joins, i've been searching individual tables (e.g. SELECT *,MATCH AGAINST etc), building arrays, searching arrays again, and then building results at the end to fit into the paginator. Now the search is taking too long to perform, and i need a leaner alternative. not to mention theres way too many lines of code, and i just know theres a better way.

There must be a very simple way to achieve the following searches using table joins, can anybody please help me with 3 search examples below so i can try to understand joins better?

Search 1:
State + Category only

Search 2:
State + Category + Keyword

Search 2:
State + Category + Postcode

If there is no postcode, the others still need to display the data
filtered by distance from a default postcode of 2000.

I'd really appreciate if anybody has a few minutes free to help out here, and hopefully teach me something about effective table joins and searching. I've omitted the extra fields and tables from the real structure, and just left the relevant ones above - if theres anyhing missing or not making sense please let me know and i'll fix up asap.

How To Query Date Between?
I have table name "actionlog",and one field in there is "date_time"
date_time (Type:datetime) example value : 11/1/2006 11:05:07

if I'd like to query date between 24/07/2006 to 26/07/2006(I don't
need time),how to write SQL command?

select * from actionlog where date_time 24/07/2006 AND date_time <
24/07/2006 ??

Date Query
suppose i had the follwing table with values

Quote: id booking_from booking_to status
1 2007-02-08 2007-02-19 1
2 2008-03-12 2008-04-22 1
suppose for the month 2007-02 i had to show the days which has been booked in array..How to perform the query...
also perform the query for the month 2007-04

Query For A Date
I want to select records that have an expiration date of 1 month before the current date on.
The query looks something like this:
SELECT first_name, last_name
FROM members
WHERE exp_date >
The exp_date is stored as a UNIX timestamp.

Date Query
$result = mysql_query("SELECT DISTINCT area FROM pubs where location='VOP' (and renewal > 'CURRENT_DATE') order by county",$db);
The above query doesn't work.
What is wrong?

DATE Query
I would like to return results for month to date.
I tried below, but it does not work. Can someone help me?


PHP Code:


SELECT * FROM myTable WHERE DATE_SUB(CURDATE(), INTERVAL (DAYOFMONTH(CURDATE())) DAY <= timestamp;

Date Query
Here's my code:

$hourdiff = "+1";
$timeadjust = ($hourdiff * 60 * 60);
$date = date("F j, Y, g:i a",time() + $timeadjust);
$sql = "INSERT INTO `printed` (event, date)
VALUES ('$event','$date')";

Which works perfect but when I use this query:

SELECT date FROM printed WHERE event ='event' ORDER BY date DESC LIMIT 1;

The query ignores AM vs. PM. For example, October 14, 2004, 8:59 am shows up newer than October 14, 2004, 3:59 pm. Until 8:59 pm comes along, the morning entry shows as the latest.

Date Query
I have two tables with timestamp columns,
the issue is that the dates do not match up exactly so if i try to insert information from each table into a third table, i can't use a simple WHERE TABLE1.TIME = TABLE2.TIME statement.
I know that MySQL has TIMEDIFF and DATEDIFF functions
so i can calculate the nearest time in table2 for a particular record in table1.
The trouble is that I can't figure out a way to loop through all
the records in table1.

Select Query (date)
How would I set the WHERE condition to select the fileds below to select only those who were placed 2 years ago?

mysql> SELECT placement_date, name, age
-> FROM table1
-> WHERE


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'.


Is Between Date More Efficient For Query?
PHP

//grab rows from yesterday
WHERE (month(articles.date) = month(now()) AND
dayofmonth(articles.date) = (dayofmonth(now())-1) AND
year(articles.date)=year(now()))




Syntax For Date Query
I am creating a search form that would give a list of records based on a start and end date. What would be the syntax for the query?

This is what I thought it might be...but doesn't seem to work.
SELECT *
FROM employee_time
WHERE `date` >= 'starttime' and 'date' <= 'endtime' and eid = 'analyst'

Date To Days Query
I need to update one of our mysql tables, which has about 60,000 entires and
correct the amount of days remain on each data record. An example of one of the
data entires is:


memid days regdate expdate
--------------------------------------
625290 | 5 | 2003-07-15 | 2003-08-16

now the days should be 14 and not 5 days. I have been trying to update the table
with a single SQL query but haven't come up with a way to do this.. I'm sure
it's something simple but I can't seem to come up with it. What is the best way
to accomplish this in a single query to update the entire table so all the
"days" are accurate according to the "expdate", and change the "days" so they
are correct?

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?

Latest-date Query
I am trying to get all records that share the most recent "RatesUpdated" datetime value from 1 table. I am doing the below query and I keep getting the following syntax error: "#1111 - Invalid use of group function"
SELECT t1.Product, max(t2.RatesUpdated) FROM `lqdp_mortgage_rates` t1, `lqdp_mortgage_rates` t2
WHERE t1.RatesUpdated = max(t2.RatesUpdated)
group by max(t2.RatesUpdated)

Join Query By Date
I've these tables:
- PERSON (id,name,age,....)
- EXAM (id,date,note,exam_type,id_user)

One person has 0 or more exams.

I have to do this report:

name, age, date, note, exam_type

This looks easy, but I have to list for each person, his/her LAST EXAM GIVEN. I mean, only the last exam must be shown for each person, and well, if person has no exam yet... to show blank (if possible)

Two Where Date Clauses In Query
I'm trying to teach myself sql and am struggling on getting a query to work.
Basically, i want to find all records listed after a certain date, but so long as they don't already exists before another date.

For instance, it should do something like:

SELECT * from table
WHERE date > "2006-06-20"
BUT don't display if there are date entries < "2006-06-19";

So, if there are values in the table with a date after the 20th June that don't have any entries before the 19th June then they will be displayed.

INSERT Query With Random Date
I have about 2,000 entries to add to my database and I want each one to have a random date of between, for instance, 2007-01-01 and 2007-03-28 [today].

Any ideas on what's the best way of doing this?

I did try and come up with a script that grabs a line, updates it and then moves on to the next line, but I keep getting "This page will repeat forever" errors coming up.

Query That Duplicate Row And Increment Date
I have a table EVENT
id date duration
1 2006-01-01 3
2 2006-04-23 5
3 2006-10-01 0

is possible made a query that do it?

id date
1 2006-01-01
1 2006-01-02
1 2006-01-03
1 2006-01-04
2 2006-04-23
2 2006-04-24
2 2006-04-25
2 2006-04-26
2 2006-04-27
2 2006-04-28
3 2006-10-01



Format Date In A Select Query
I'm storing dates in a db using the DATE-datatype in the YYYY-MM-DD format, now i want to show the dates on my webpage in the european DD-MM-YYYY format.

I have written the following SELECT-query but it doesn't seem to work.
The date is not shown when i show the results of the query.
The column where the dates are stored is called "startdate".

MySQL
$query  = "SELECT date_format(startdate, '%d %c, %Y'),cat,locatienaam,adres,postcode,stad,telefoon,contactpersoon FROM datasheet ";

this is what I do with the result of the query

MySQL
PHP

$result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)){    echo "<h2>{$row['locatienaam']} </h2>" .        "<h2>{$row['startdate']}</h2>" .         "<p>{$row['omschrijving']}</p> <br><br>";}

And it doesn't show the date when I use the SELECT query shown in the first post of this thread.

Transform '07,01,06' Into A Date Format With Just A Query
I've been handed just about the worst HTML/PHP/MySQL site ever scrapped together. While we're in the process of rebuilding the site from scratch for our client, they desperately need some data pulled from their DB.

Originally the data was dumped to files but due to attempted injection attacks, the table has grown so large it times out. So I'm trying to pull the data directly but I have a huge problem. I need to pull all data with a date >= July 1, 2006. The problem is the dipsh*t who built this has the date field with a datatype of varchar and the date in the format of &#3907;,01,06'. Obviously I can't do a date comparision check with that so how can I transform this data into a correct date format using only a query? I do NOT want to go in and start coding in this site. It's a live site and I'm afaid anything I do will break it.

It's MySQL 3.23.57 and all I have access to is PHPMyAdmin. PLEASE help me!!! Someone work a little query magic for me.

Date Field In Mysql Query
Just after a bit of advice or guidance on the best way to go about an issue i have..

At present i have a simple user form with drop down lists for the user to enter a date. (eg. 1,2,3, - Jan, feb, mar, - 2006,2007 etc..) as -$day -$month- $year...

All other input areas on this form are text and will go in a Varchar fields so will not be an issue...

My query is what is the best way to handle this date, and how..?
I undestand Mysql needs the date as yyyy mm dd to be in a date field..
Im just really unsure of how to put my format date in to a date field on the table and query it out so it displays in my format again..

Ive done quite of bit of searching for this and seen many suggestions including using INT and Varchar fields so i am really confused as the best and correct way to go about this..

Query Dates Within 1 Week From A Date
I'm fairly new to PHP and have done some basic work with mysql but am not sure how to approach this. I'm trying to figure out how to create a query with PHP to get all rows with a datetime from 1 week ago to the current timedate.

Note: I'm also not sure how to find a date for 1 week ago with PHP. Any help would be great.

Date Difference In MySQL Query (3.23.50)
I am trying to calculate the age of my customers. The birthdates are stored: 19621222

I am trying:

Select (Current_Date - BirthDate)/365 as Age from Customers

Of course that is not the solution. Is there a function i can use?

How To Create A Query To Get Top 5 Item For Each Date
I have running out of idea on hw to create a query to get each day top 5 item with a date range given more than 1 month or more.

meant: if i have a date range from 2006-01-23 to 2006-10-23, then i want to get the latest 31 days data only with each day TOP 5 item. How?

Lets say i have a table with this keyword: MyDate;Item;CountItem;

The date range is unknown and can be any range selected by user.

I am trying to think of put auto increament for each day with CountItem desc and each day the column of auto-increament is set to 5 only so at last i can just get all the data from it. But the question is i dunno how to do it?

Anyone have better solution? I know if using store procedure then can do this but is it can done without store prodedure?

First Group By Date, Then Count... All In One Query?
I have a mySQL database that has individual records for each time a page on my site is hit. What I'm trying to do is set up a tracking system which will display the hit counts for each page, by month, for the past three months, and ordered by total hits over that timespan.

The table is simple:
visitedPage | visitedTime

My current query is this:


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