Is there a way to select rows from a DB where the timestamp is in a certain year? I don't have a specific timestamp, just a range (ex. all timestamps within the year 2009). Is there a way to do this? How else might I go about doing something like this? Thanks for your help!
-iMaster
Use:
WHERE timestamp_col BETWEEN STR_TO_DATE('2009-01-01', '%Y-%m-%d')
AND STR_TO_DATE('2009-12-31', '%Y-%m-%d')
Any functions performed on a column mean that an index, if one exists for that column, can not be used.
I used the STR_TO_DATE function to ensure that whatever date provided as a string could be interpreted by MySQL as a TIMESTAMP.
Reference:
STR_TO_DATE
As simple as:
SELECT * FROM table WHERE YEAR(timestamp) = '1999'
Use FROM_UNIXTIME similar to this:
SELECT
FROM_UNIXTIME(my_timestamp, '%Y') AS year
FROM
table_name
WHERE
FROM_UNIXTIME(my_timestamp, '%Y') = 2009;
Where 'my_timestamp' is the name of your timestamp column.
Alternatively you can also convert it to a DATETIME
If you convert it to datetime you can do it by using the mysql DATE_FORMAT function which allows you to take a DATETIME and format it as a date. Then group by that column.
private function _formatDate() {
if ($this->_granularity == 'month') {
return '%y/%M';
}elseif($this->_granularity == 'day') {
return '%y/%M/%d';
}
}
public function getmyquery() {
$query = "
SELECT count( * ) as visits, DATE_FORMAT( `myOriginalDateField` , '".$this->_formatDate()."' ) AS mydate
FROM `mys`
WHERE id = ".$this->_Id."
GROUP BY mydate
ORDER BY mydate ASC
";
return $query
}
An important addition to the excellent suggestions already given here: if you plan on executing this query as a part of rendering your pages (as opposed to running this as a one-off report), you should really consider performance. Indexes won't help you much if you're post-processing the column value with a function before comparing it to something.
In that case, I would consider creating a separate database column that contains JUST the year, or just the month, etc.
Related
I have 'dob' field that is varchar type and the data is '12/07/1988' and '10/30/1988' inside my database.
I want to filter the record base on 'dob' date range.My input date range is '01/01/1988' and '31/12/1988' but all others record also come out.
This is my code,anyone can help?
SELECT
dob
FROM
`tblcustomers`
WHERE
DATE_FORMAT(STR_TO_DATE(dob, "%m/%d/%Y"), "%d/%m/%Y") >= '01/01/1988'
AND
DATE_FORMAT(STR_TO_DATE(dob, "%m/%d/%Y"), "%d/%m/%Y") <= '31/12/1988';
Thank you.
try it...
SELECT dob FROM tblcustomers where DATE_FORMAT(STR_TO_DATE(dob, '%m/%d/%Y'), '%Y-%m-%d') between '1988-01-01' and '1988-12-31'
It is better to use DATE/DATETIME than VARCHAR, otherwise it will waste time converting string to date all the time when you have queries.
You can simply change your dob field to DATE
and then filter the record like this
SELECT * FROM tblcustomers WHERE dob BETWEEN '1988-01-01' AND '1988-12-31'
Notice: When using BETWEEN...AND, '1988-01-01' & '1988-12-31' will not included
so you may decrease the start-day 1 day and increase the end-day 1 day
it may look like this
SELECT * FROM tblcustomers WHERE dob BETWEEN '1987-12-31' AND '1989-01-01'
or easier way similar to what you have done, this one is also possible
SELECT * FROM tblcustomers WHERE dob >= '1988-01-01' AND dob <= '1988-12-31'
Date range will work on sql date type not on varchar ,so first change it to date type and insert date in format yyyy-mm-dd then you can use range it will work
You can try this. I hope it will help you.
$from_date = date("Y-m-d",strtotime('01/01/1988'));
$to_date = date("Y-m-d",strtotime('31/12/1988'));
$query = "SELECT * FROM tblcustomers WHERE from_date >= '".$from_date."' AND to_date <= '".$to_date."'";
is their any query to pick certain date between two time stamps?The Problem is these two times stamps are set in two diffrent fields
SELECT * FROM table WHERE fs_from > theDate AND fs_to < theDate;
I suggest to use prepared statements and insert a date object into the query.
In my opinion you can try in this way (If I really understood your question)
SELECT myFields FROM myTable
WHERE myCertainDate BETWEEN fs_from AND fs_to
Try this:
SELECT *
FROM table
WHERE fs_from > 'some date'
AND fs_to < 'some other date'
Which date do you want? You can choose a random date by doing:
select t.*,
date_add(t.fs_from, interval cast(datediff(fs_to, fs_from) * rand() as int) day
) as ArbitraryDateBetweenTwoDates
from table t
I know my question is similar to other question already answered but my issue is different because I need some alternative or advice no how to go the other way around.
My issue is: I want to get values between either two dates or one according to what user wants..
When User request data of one day.. php query data successful.. but problem is when data requested is between two dates..
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '$first_date' AND
`meta_transaction_date` <= '$second_date' ");
return $query->result();
I get an empty set...
So I thought may be the values are not submitted correct.. so I echoed the values to see if they are correct or not. I find they are correct...
$first_date = 09/13/2014;
$second_date = 09/19/2014;
But if I try to put the value like
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014' AND
`meta_transaction_date` <= '09/19/2014' ");
return $query->result();
I get my result back correct.. so is there anything am doing it wrong??
Change the type of meta_transaction_date to DATE as that is what it is! Also use the standard 'yyyy-mm-dd' when passing in DATEs.
Your problem probably stems from string ordering of the 'mm/dd/yyyy' US date format which is horrible for coding. If you wish to display the DATE in this format, convert it when SELECTing the final output.
MySQL has a built in function called Between that you can use like this:
SELECT * FROM table_name WHERE date_column BETWEEN 'start_date_parameter' AND 'end_time_parameter'
Try to cast the date first , and then with between statement:
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` BETWEEN
date_format(str_to_date('$first_date', '%d/%m/%Y'), '%Y-%m-%d') AND
date_format(str_to_date('$second_date', '%d/%m/%Y'), '%Y-%m-%d')");
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014'
AND `meta_transaction_date` <= '09/19/2014' ");
Since the above seems to be working fine, the problem is in your code.
$query = $this->db->query("SELECT `meta_transaction_date` FROM meta_receipt_data WHERE
meta_transaction_date BETWEEN "
.date( "Y-M-d", ( strtotime($first_date) ) )." AND "
.date( "Y-M-d", ( strtotime($second_date) ) ) );
A word of advice, do not use queries like SELECT * as they will degrade performance of your application. And I just read in your comment to your own question:
I have set the type as Varchar
Do not do that. It is best to use the DATE type to store dates. You can use the query:
ALTER TABLE `meta_receipt_data`
MODIFY `meta_transaction_date` DATE NOT NULL;`
Well, that is assuming you wish to keep the column to not accept null values.
I found that the value had space before and after so I use $first = trim($first_date); and problem solved...
I am trying to query a small database by date, my date table data is stored in time 2014-02-04 . how can I convert that and check it against todays date.
This is what I have but I am getting a few errors
$q = 'SELECT count(*) as count FROM SHOW WHERE date('Y-m-d', strtotime
('SHOW_DATE') ='.$db->qstr(date()).' AND CONTACT='.$db->qstr($name);
if(!$rs = $db->execute($q)){
force_page('core', 'error&error_msg=MySQL Error: '.$db->ErrorMsg().'&menu=1');
exit;
} else {
$today_count = $rs->fields['count'];
$smarty->assign('today_count',$today_count);
}
Thanks a lot.
You can convert show_date to a date format using FROM_UNIXTIME function. And then compare the date part of it with your input date value.
Example:
SELECT count(*) as count FROM `SHOW`
WHERE date( from_unixtime( `SHOW_DATE` ) ) = ? AND CONTACT=?
Use prepared statement to bind input values to the place holders.
To find a row containing a DATE matching the current date, use CURDATE():
SELECT column FROM table WHERE col_date = CURDATE()
I am going to give order in query like:
SELECT * FROM `sales_report` ORDER BY `cancel_date`, `pur_date`
But its not working could you please check what is wrong in this query because its not ordering dates?
pur_date type is date and cancel_date type is text so is it issue ? I can't change its type.
I echo a different think like:
if(cancel_date != ''){
$transection_date = cancel_date;
}
else {
$transection_date = pur_date;
}
Try to use STR_TO_DATE() function:
SELECT
*
FROM
`sales_report`
ORDER BY
STR_TO_DATE(`cancel_date`, '%Y-%m-%d'), `pur_date`;
As zerkms mentioned in comments: You should use format specifiers, dependent of your text values in cancel_date column.
SELECT *, CAST(`cancel_date` as DateTime) cancelDate
FROM `sales_report`
ORDER BY `cancelDate`, `purDate`
This should work