how to select the 5 latest row from my mysql - php

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

Related

PHP: Combine these two SQL queries into one

I use MariaDB and have a table where each row has a date and a score.
I want to first show the rows where the date is 3 days old or newer, sorted by the score - then show the rest (more than 3 days old) sorted by date.
Since my date is stored in unix time, it's fairly easy to have php calculate 3 days from before now and use that as my $scoreTimeLimit variable in the below:
Here are my two queries:
SELECT * FROM myTable WHERE myDate > $scoreTimeLimit ORDER BY myPopularityScore DESC
SELECT * FROM myTable WHERE myDate < $scoreTimeLimit ORDER BY myDate DESC
However, I would VERY much like to have only 1 query instead of two. Can it be done...?
This is a job for UNION.
SELECT * FROM (
SELECT 0 ord1, NOW() as ord2, *
FROM myTable WHERE myDate > NOW() - INTERVAL 3 DAY
UNION ALL
SELECT 1 ord1, myDate as ord2, *
FROM myTable WHERE myDate <= NOW() - INTERVAL 3 DAY
) a
ORDER BY ord1, ord2 DESC, myPopularityScore
The inner query gives you a single result set with a couple of extra columns added on to help you manage your sorting.

Select max and min values in one sql query

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

php - get different dates in while loop

I have this while loop:
<?php
$q=mysql_query("SELECT * FROM xeon_stats_clicks WHERE user='".$userdata['username']."' AND typ='4' ORDER BY data DESC LIMIT 8") or die(mysql_error());
while($clickData=mysql_fetch_assoc($q)):
$r=mysql_query("SELECT sum(value) FROM `xeon_stats_clicks` WHERE user='".$userdata['username']."' AND typ='3' AND data='".date("Y/m/d")."' ORDER BY data DESC LIMIT 8");
echo mysql_result($r, 0);
endwhile;
?>
This will just give me the sum of the value row for today only. How can I do so I get the data from the last 7 days?
there is no need to specify the certain date for it will give you on this specific date, another comment suggested the use of 'between' but I like the use of '>' only in this case,
for example:
SELECT sum(value) FROM xeon_stats_clicks WHERE
user=.$userdata['username'] AND type='3' AND date > CURDATE() -
INTERVAL 1 WEEK ORDER BY date DESC LIMIT 8"
SELECT SUM( value ), `data`
FROM table
WHERE ( `data` BETWEEN CURDATE() AND CURDATE() - INTERVAL 1 WEEK )
GROUP BY `data`
for example.
try another where statement:
DATEDIFF( CURDATE(), CURDATE() - INTERVAL 1 WEEK ) = 7
and show your where statement

Mysql get results from todays date and forward

I am using opencart and wrote a new module to grab products that are coming soon. yet it still shows products even from before todays date.
my sql statement:
SELECT *, DATE_FORMAT(date_available, "%M %d, %Y") as `comingdate` FROM `product` WHERE `date_available` >= '.DATE("Y-m-d").' ORDER BY `date_available` DESC LIMIT 20
what is wrong with that statement?
"SELECT *, DATE_FORMAT(date_available, '%M %d, %Y') as `comingdate` FROM `product` WHERE `date_available` >= '".date('Y-m-d')."' ORDER BY `date_available` DESC LIMIT 20"
Remember, date_available is a string. You need the single quotes there.

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