Select max and min values in one sql query - php

i have a table that has records with its timestamp. now i have a requirement to get the oldest record and the newest record
9/10/2014 6:54
9/10/2014 6:53
9/10/2014 6:51
9/8/2014 8:09
9/8/2014 7:00
9/5/2014 7:38
9/5/2014 3:57
9/5/2014 3:51
9/4/2014 11:09
9/4/2014 8:39
currently this is how i obtain them by sending two database calls which slows downs processing
$new_timestamp = mysql_query("SELECT TIMESTAMP FROM $rectable ORDER BY TIMESTAMP DESC LIMIT 1");
$col_old = mysql_fetch_assoc($new_timestamp);
$old = $col_new['TIMESTAMP'];
$new_timestamp1 = mysql_query("SELECT TIMESTAMP FROM $rectable ORDER BY TIMESTAMP ASC LIMIT 1");
$col_new = mysql_fetch_assoc($new_timestamp1);
$new = $col_new['TIMESTAMP'];
is there any way to optimize this code and fullfiill requirement without sending two database calls, througha special query or a stored proceedure

You can use max and min to get the newest and oldest timestamps
select max(timestamp), min(timestamp) from mytable

Try with UNION
select TIMESTAMP as old FROM $rectracktable ORDER BY TIMESTAMP DESC LIMIT 1
union all
select TIMESTAMP as new FROM $rectable ORDER BY TIMESTAMP ASC LIMIT 1

Related

mysql fetch records which have been added in the last 10 seconds?

I want to fetch records that have been added in the last 10 seconds. I have a "zaman" column which has the timestamp of the record that tells when it has been added.
I have tried this one, however, it doesnt work (no errors)
mysql_query("SELECT * FROM notifs where writer='".$member[nick]."' AND
zaman >= DATE_SUB(NOW(),INTERVAL 10 SECOND) ORDER BY id DESC limit 5")
or die(mysql_error());
What is the correct way to do it ?
When a new record is saved, record it's time saved. Then, when running the fetch query, get all values that are greater than or equal to current time - 10.
assuming zaman is a epoche timestamp...
mysql_query("SELECT * FROM notifs where writer='".$member[nick]."' AND
zaman >= UNIX_TIMESTAMP()-10 ORDER BY id DESC limit 5")
try this
mysql_query("SELECT * FROM notifs where writer='".$member[nick]."' AND zaman >= (NOW() - INTERVAL 10 SECOND) ORDER BY id DESC limit 5")

Fetch rows from mysql table if a condition satisfies in php

I have a table like this
my table is here
I need to fetch the table such that the valid_from date is less than the the date which I have(date cannot be current date).
For example. If my date is 02-04-2015, I should get the row with id 120.
Plz help me to do this in php
Please try below quewry :
$input_date = "02-04-2015";
$your_date = date("Y-m-d",strtotime($input_date));
$sql = "SELECT * FROM `table_name` where DATE(validFrom) < '".$your_date."'";
as per your example
SELECT * FROM `your_table_name` where validFrom < '02-04-2015' order by validFrom desc LIMIT 1
or
SELECT * FROM `your_table_name` where validFrom < '02-04-2015' order by validFrom asc LIMIT 1
set order by as per your expectation of output
here you want to pass date as per your date format

SQL selecting records with dates before today

I have a mysql DB with tables, of which in the one table I have a date type field, I want the most recently passed date - so I want it to order by dates descending, but only take records from before today, and then take only the top most one using the LIMIT function, and also there is the addition of the WHERE clause being that the offer must be for the selected city.
$result = mysql_query("
SELECT * FROM offers
WHERE city = ".$_SESSION["city"]."
ORDER BY exp_date DESC
LIMIT 0, 1");
ADD another condition to where clause
$result = mysql_query("
SELECT * FROM offers
WHERE city = ".$_SESSION["city"]." and Date < CURRENT_DATE()
ORDER BY exp_date DESC
LIMIT 1");
SELECT * FROM deals WHERE city = 2 AND exp_date < CURDATE()
ORDER BY exp_date DESC LIMIT 0, 1
Add the following condition to Where:
... and exp_date < CURDATE()
See http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html.

how to select the 5 latest row from my mysql

I wanted to know the sql command to retrieve 5 latest row from my table? Below is my sql query. How am I going to do, in order it can select the 5 latest row base on row no to be process?
$query =
"SELECT lat, lng, DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS
datetime FROM markers1 WHERE 1";
You need to order the results, and set a limit.
Assuming datetime is what you wanted to order on:
$query = "
SELECT
lat,
lng,
DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS datetime
FROM markers1 WHERE 1
ORDER BY datetime DESC
LIMIT 5
";
EDIT:
To answer OP's comment: "result that i get is start for Row 50 for first query and it follow by 49,48,47,46 Is that possible i can get this start frm row 46,47,48,49,50 ?"
You could either do this with the result in PHP, by fetching the rows and storing them in an array and reversing the array. I don't believe you can efficiently loop through a mysql result resource in reverse.
To do this in the SQL query, you need to create a temporary table with the original query:
$query = "
SELECT
lat,
lng,
DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS datetime
FROM (
SELECT
lat,
lng,
datetime
FROM markers1 WHERE 1
ORDER BY datetime DESC
LIMIT 5
) AS tmp_markers
ORDER BY datetime ASC
";
The result of the initial query is used as the table to search in a new query, that orders by datetime ascending. I had to apply the DATE_FORMAT on the outer query because we need the datetime field to order by again.
just add:
ORDER BY datetime DESC
LIMIT 5
The best way to do this is to add a row number and then reverse your query based on that, since we don't have any guarantees that your datetime field increments chronologically; and I'm also assuming that by 5 latest rows you mean the last 5 added to the table, not the 5 with the most recent datetime.
SELECT
lat
, lng
, DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS datetime
, #rownum:=#rownum+1 `RowNum`
FROM
markers1
, (SELECT #rownum:=0) `r`
WHERE 1
ORDER BY RowNum DESC
LIMIT 5
Check out this dude's blog for the rownumber solution I used.
Might be a very late answer, but this is good and simple.
select * from table_name order id desc limit 5
This query will return a set of last 5 values(last 5 rows) you 've inserted in your table
Check out my query for last 5 entry
SELECT * FROM notices where organizationid = $orgid ORDER BY `notices`.`id` DESC LIMIT 5
So, Most Important is ORDER BY notices.id DESC LIMIT 5

PHP / MySQL - Construct a SQL query

Im having a little trouble constructing a query.
I have a table with 3 columns.
id - day - pageviews
What i basically want to do is get 8 id's from the table where the pageviews are the highest from the last 60 days.
The day column is a datetime mysql type.
Any help would be great, im having a little trouble figuring this one out.
Cheers,
Almost the same as TuteC posted, but you'll need a group by to get what you need...
SELECT id, SUM(pageviews) totalViews
FROM table
WHERE DATE_SUB(CURDATE(), INTERVAL 60 DAY) <= day
GROUP BY id
ORDER BY totalViews DESC
LIMIT 8
Do something like this:
SELECT id FROM table_name
WHERE DATE_SUB(CURDATE(),INTERVAL 60 DAY) <= day
ORDER BY pageviews DESC
LIMIT 8;
$sixtyDaysAgo = date('Y-m-d',strtotime('-60 days'));
$sql = "SELECT id
FROM table_name
WHERE day >= '$sixtyDaysAgo 00:00:00'
ORDER BY pageviews DESC
LIMIT 8";
If each row is a number of pageviews for that day, and you're looking for the highest total sum of 60 days' worth, then you'll need to total them all and then grab the top 8 from among those totals, like so:
$sql = "SELECT id
FROM (
SELECT id, SUM(pageviews) AS total_pageviews
FROM table_name
WHERE day >= '$sixtyDaysAgo 00:00:00'
GROUP BY id
) AS subselect
ORDER BY total_pageviews DESC
LIMIT 8";

Categories