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
Related
Now currently facing a problem that is..
My table name is schedule
One of the data field is 'Depart'
the record is
row 1 = 19-08-2012 08:00:00AM,
row 2 = 19-08-2012 12:00:00PM,
row 3 = 20-08-2012 07:00:00PM,
I just want to display the date only and it is distinct
mysql_query(Select distinct depart from schedule);
This display date and the time.
Any one here know how to display the date only?
Example
SQL (recommended)
SELECT DISTINCT DATE( depart )
FROM `tbl`
PHP
$d = "19-08-2012 08:00:00AM";
echo date("d-m-Y",strtotime($d));
You can use DATE_FORMAT() function in the Mysql, as follows :
select DATE_FORMAT(distinct(Depart),'%m-%d-%Y') from schedule
Yes, use DATE:
SELECT DISTINCT DATE(`depart`) FROM `schedule`
Okay guys, this probably has an easy answer but has been stumping me for a few hours now.
I am using PHP/HTML to generate a table from a MySQL Table. In the MySQL table (TimeRecords) I have a StartTime and EndTime column. In my SELECT statement I am subtracting the EndTime from the StartTime and aliasing that as TotalHours. Here is my query thus far:
$query = "SELECT *,((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date
BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
ORDER BY Date
";
I then loop that through an HTML table. So far so good. What I would like to do is to add up all of the TotalHours and put that into a separate DIV. Any ideas on 1) how to write the select statement and 2) where to call that code from the PHP/HTML?
Thanks in advance!
Try this
$query= "
SELECT ((EndTime - StartTime)/3600) AS Hours, otherFields, ...
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31' ";
$records =mysql_query($query);
$sum= 0;
while($row=mysql_fetch_array($records))
{
echo"$row['otherFields']";
echo"$row['Hours']";
$sum+=$row['Hours'];
}
echo" Total Hours : $sum ";
Just use a single query with a Sum(). You could also manually calculate it if you're already displaying all rows. (If paginating or using LIMIT, you'll need a separate query like below.)
$query = "
SELECT Sum(((EndTime - StartTime)/3600)) AS SumTotalPeriodHours
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31'
";
You can do this in the same query if you have a unique id using GROUP BY WITH ROLLUP
$query = "
SELECT unique_id,SUM((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
GROUP BY unique_id WITH ROLLUP
ORDER BY Date
";
In this instance the last result from your query with contain NULL and the overall total. If you don't have a unique ID you will need to do it in PHP as per Naveen's answer.
A few comments on your code:
Using SELECT * is not considered good practice. SELECT the columns you need.
Not all months have a day 31 so this may produce unexpected results. If you're using PHP5.3+, you can use
$date = new DateTime();
$endDate = $date->format( 'Y-m-t' );
The "t" flag here gets the last day of that month. See PHP docs for more on DateTime.
In my code, I am trying to find items in an activities table that are within the last day. This query is not returning any results, are there any problems with it? Is there a better query?
$curday = time() - (24*3600);
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > '$curday'";
There are two choices here, you can get and format the date through PHP or use SQL language to do it. I prefer to do it within the SQL, it also allows me to use the same query in a MySQL client.
This question is essentially the same thing: MySQL SELECT last few days?
This would be the new query:
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > DATE_ADD(CURDATE(), INTERVAL -1 DAY)";
you can try with unix function 'mktime' to get value of yesterday ..
as
$curday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
for reference
if your database will mysql only then you can extract yesterday in sql itself..
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY)
one more thing if timestamp is your column name don't put this column inside single quote ..
What you can use is DATE_SUB. This can be used as follows
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > date_sub(current_date, interval 1 day)
This way you don't need to work with current date in PHP
in Informix it would be (TODAY - 1) if the column is type DATE
I have a variable called $date with a date format like 2012-01-30. On the other hand I have a field called srt_date_sortie in a mysql table. The format of that field is like 2012-01-30 11:31:00. I would like to select all records where $date and srt_date_sortie have equal dates not taking into consideration the time. Hope someone can help.
mysql_query("SELECT * FROM sorties WHERE srt_date_sortie = '$date'");
Here below how I build $date :
++$input;
$test=$input." days";
$date=date('Y-m-d', strtotime($test));
Thank you in advance for your replies. Cheers. Marc
For performance reasons you should avoid comparing against a derived column like DATE(srt_date_sortie) as this will prevent any indexes from being used. This negates a few of the solutions already posted.
The most efficient way of querying against your DATETIME field is by using a range query like:
mysql_query("SELECT * FROM sorties WHERE srt_date_sortie BETWEEN '$date 00:00:00' AND '$date 23:59:59'");
Unless you need all of the rows from the table the SELECT * could be inefficient, just list the rows that you need to retrieve.
Change your query with BETWEEN keyword for date start time and end time.
You can format date using DATE_FORMAT in mysql
mysql_query("SELECT * FROM sorties
WHERE DATE_FORMAT(srt_date_sortie,'%Y-%m-%d') = '$date'");
mysql_query("SELECT * FROM sorties WHERE DATE(srt_date_sortie) = '$date'");
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date
mysql_query("SELECT * FROM sorties WHERE srt_date_sortie LIKE '%2012-01-30%'");
$date=date('Y-m-d H:i:s', strtotime($test));
Use it
Check the TIMESTAMPDIFF mysql function
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
-> 128885
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.