PHP/MySQL Sort By Date - php

I'm trying to pull records out of my database based on the oldest date.
The MySQl table looks like this:
status, date, last, url
1, 2010-12-30 17:59:54, 2011-01-03 06:26:04, site1.com
1, 2010-12-28 12:16:10, 2011-01-03, 06:25:24, site2.com
The date and last rows are datetime.
Here are two types of queries I tried:
mysql_query("SELECT * FROM links WHERE status=1 ORDER BY last DESC LIMIT 0,25");
mysql_query("SELECT * FROM links WHERE status=1 ORDER BY DATE(last) DESC LIMIT 0,25");
The query works for the most part but always leaves some of the oldest records out...
Any ideas?
Thank you

I'm going to assume "last" means last clicked or updated right? I also think you want ascending order (12/20, 12/21) because you want the oldest dates first. "ORDER by last LIMIT 25" should be fine as ASC is implicit.

What are date and last's data types? timestamp or ?
try this:
mysql_query("SELECT * FROM links WHERE status=1 ORDER BY UNIX_TIMESTAMP(last) DESC LIMIT 0,25");

Related

Reverse results of PostgreSQL after using ORDER BY

I have a query where I need to select the latest 25 entries to my database, but inverse the order of the results of that select.
I've come up with:
SELECT indexID, datetime, temperature FROM dataB WHERE userID="4236" ORDER BY indexID DESC, datetime ASC LIMIT 25
But I'm still getting the results in chronological order starting from newest, but I want chronological oldest to newest WITHIN those 25 newest. I'm using PHP's pg_fetch_row() and creating a concatenated string with the results and feeding that into a Morris.js graph, where my data is being graphed backwards because of this query.
How do I reverse the results of a query?
You should try this , first fetch data in descending orders after that use as temporary table and again select in ascending order
SELECT indexID, datetime, temperature FROM (SELECT indexID, datetime, temperature FROM dataB WHERE userID="4236" ORDER BY indexID DESC LIMIT 25) temp order by indexID ASC
Instead of putting the results directly into a string, load them up in an array. When the array is full, use the array_reverse function to reverse the order of the elements in the array. You can now build your string and pass the data to your Morris graph.
Documentation: http://php.net/manual/ro/function.array-reverse.php
Try to add an offset along with a limit to your query. Below example shows an offset which basically gets the total number of rows that match your query and subtracts 25 from it to offset you to start from the "25th last" record which matches your query:
SELECT indexID, datetime, temperature
FROM dataB WHERE userID="4236"
ORDER BY indexID DESC, datetime ASC
LIMIT (( SELECT COUNT(indexID) FROM dataB WHERE userID="4236" )-25), 25;

SQL Query matching two fields

I currently have a table called cc_site, in this table I store the results of pings from different ip addresses.
The table has four fields:
auto increment ID field
date (which includes time)
IP address
status (used to determine if the ping was successful or not).
I'm trying to create a query which will give me the latest result based off the date field for an individual ip address. The code I'm currently using is below but it doesn't work unless the IP I'm using in the query is the latest entry in the table.
$query = "SELECT *
FROM cc_site
WHERE ip='$host'
AND Date IN (
SELECT max(date)
FROM cc_site
)";
I knew the query is incorrect however I have not been able to find code that would perform the query I need.
Any help would be great.
No need of that sub-query. Use can use ORDER and LIMIT instead -
SELECT * FROM cc_site WHERE ip='$host' ORDER BY `date` DESC LIMIT 1
This will sort the records in descending order according to date and return the record with highest record.
select * from cc_site
where ip='$host' and date in(select max(date) from cc_site where ip='$host');
I think this might give you the answer

How to select from last to first row in mysql

Whenever a query like
"select * from table where userid=xx" is done, the mysql fetches these values from
first row to last row of table.
But I want to select from last to first so that recently updated values are displayed first in the results.
I cannot do "select * from table where userid=xx order by time DESC" because there is no time column in table.
I just want recently updated items in the table displayed first.
$result= mysql_query("SELECT
(SELECT column FROM table WHERE [condition] ORDER BY column LIMIT 1) as 'first',
(SELECT column FROM table WHERE [condition] ORDER BY column DESC LIMIT 1) as 'last'");
$row=mysql_fetch_array($result);
echo $row['first'];
echo $row['last'];
If you have any auto-incrementing field you could sort by that desc.
You must provide a column to order by in order to guarantee results. So you will have to either change your table structure or make a decision on what to order by.
A hack would be to pull in the data in the order presented into an array, then start popping off the bottom of that array.
You either have to have a timestamp, or autoincrement id, or some other column that you want to sort by.
Just because you get rows in a certain order from a database when not using an ORDER BY clause, does not mean that they are guaranteed to be returned in that order. It also doesn't imply any order in the result set. You need a definitive field that you can use to ORDER BY, or you cannot do what you are wanting to do.
Some hack you can do for that if you don't have columns you can rely on:
SELECT * FROM (SELECT *,(#x:=#x+1) default_ordering FROM `table_name`, (SELECT #x:=0) t2) any_name ORDER BY default_ordering DESC

How to select the most recent 10 records

I have a mysql database. How do I select the most recent 10 records? Im not storing timestamps. But the most the recent records are the ones at the bottom rite? Also. How so I get the next ten , the next ten and so on on clicking a button. Kinda like a bunch of forum posts. The recent ones show up first.
I believe you have an auto increment column as a primary key you can use this column and to order by desc
select * from table order by id desc limit 10
otherwise you have a very poor database design
If you have an AUTO_INCREMENT column you can order by that in descending order then limit by 10.
But I suggest you store timestamps and order by that instead so you know you're sorting your records according to date, and not some other value that coincides with date of insertion.
In addition to what #BoltClock mentioned, prequerying the maximum ID might help the engine with what other records are retrieved... ie: if you have a million records, and most recent 10, I don't know if it will still try to query out the million, order them, and THEN dump it.. I would try something like
select STRAIGHT_JOIN
YT.*
from
( select max( IDColumn ) as MaxOnFile
from YourTable ) PreQuery,
YourTable YT
where
YT.IDColumn >= PreQuery.MaxOnFile -10
order by
YT.IDColumn DESC
limit 10
However, if for some reason, records are allowed to be deleted, you may opt to subtract a little farther back than the -10... but at least this way, the system won't even TRY to process all the other records...

Making MySQL return the table backwards

I want to make a simple news system using PHP and MySQL, right now I got a working post and read system but there is only one problem, I want it to show the 10 latest news but instead it shows the 10 oldest news.
My question is: Is there a way to make MySQL return the results from the bottom of a table or do I have to first get the number of posts and then limit it to the very last 10 ones?
Here is the insert (title and text is escaped and time is time(), poster is not done yet):
mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());
And to retrive it (addnews echos it):
$myqr = mysql_query('SELECT * FROM news LIMIT 10') or die("Error running news query: ". mysql_error());
while($myres = mysql_fetch_array($myqr))
{
addnews($myres['id'], $myres['title'], "admin", date('l jS F Y - H:i:s', $myres['time']), $myres['text']);
}
So, short: I want to read the database backwards, is it possible?
Check out the ORDER BY clause. It allows you to sort rows by a column in ascending or descending order. The following query will return 10 news items, sorted by time in descending order.
SELECT * FROM news ORDER BY time DESC LIMIT 10
Simple, just add an "ORDER BY" clause to your SQL, e.g.
SELECT * FROM news ORDER BY time DESC LIMIT 10
you need to modify your query to sort by the date it was created. something like
SELECT * FROM news order by time DESC LIMIT 10
should work for you. I think its worth noting that if you do not specify an Order by clause, the order in which results are returned is not guaranteed. Right now, you happen to be getting them ordered by the time they were inserted ascending, however you cannot safely assume that will always be the case.
Assuming that id is the primary key:
SELECT * FROM new ORDER BY id DESC LIMIT 10
Use an ORDER BY clause.
Could you not simply Order By time Descending before LIMIT 10?
use
SELECT * FROM news ORDER BY time DESC LIMIT 10
You could also use
SELECT TOP 10 FROM news ORDER BY time DESC
I believe. Not sure if the 'top' clause is SQL Server only, though.

Categories