Reverse results of PostgreSQL after using ORDER BY - php

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;

Related

MySQL - Fetching more records when ordered by integer

So, I'm writing an application to fetch records from the database, and my client has asked if I could sort the data by area. I've got the following query:
SELECT
*
FROM
customers
WHERE
account_type != 'x'
AND
account_type != 'tor'
ORDER BY
area ASC,
id ASC
LIMIT 30
The query returns 30 rows worth of data, all with an area value of 1.
I've got an AJAX query set up to fetch another 30 rows, however as I am ordering the data by area, I am unable to just fit a simple range string to my query as shown in the example below:
...
AND
id > 30
...
How would I write a query that would collect the next 30 records from the database?
Also, there is a record with an area value of 0. This is not shown as the first record in the list. Why is this? And how can I fix this?
Thanks
First, combine the where conditions into a single not in:
SELECT c.*
FROM customers c
WHERE account_type NOT IN ('x', 'tor')
ORDER BY area ASC, id ASC
LIMIT 30;
Then, for the next set, use:
SELECT . . .
OFFSET 30
LIMIT 30
This assumes that id is unique in the table. That is important, because that makes the sort stable.
Have a look at the the SELECT query documentation:
https://dev.mysql.com/doc/refman/5.7/en/select.html
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
In summary, just limit returns you x records. With the offset you can set a starting position, basically allows you for paging.
MySQL LIMIT take an optional parameter offset, so you could send in a parameter telling where to start when picking the 30 results you want
SELECT
*
FROM
customers
WHERE
account_type != 'x'
AND
account_type != 'tor'
ORDER BY
area ASC,
id ASC
LIMIT 30, 30
Should give you the next 30 rows starting from row 30

Order by field not working,but no error

I have a query like this,
select * from my_table where `status`='1' ORDER BY FIELD(city_id,548) ASC;
My purpose is to show all records from the table, but records with city_id=548 should come first.
Currently its showing all records but no desired sorting! Any ideas?
Actually it is working but you need to change it to DESC because FIELD() returns the index of the value in the parameter.
Other than FIELD() which accepts multiple parameters, you can alternatively use = if you only have one condition.
ORDER BY (city_id = 548) DESC
when city_id = 548 is true, it returns 1 otherwise 0 that is why we used DESC.
Try like this
descending order in sql is denoted by DESC keyword I think other values are smaller than 548 that's why it's not work as you expect
select * from my_table where `status`='1' ORDER BY FIELD(city_id,548) DESC;

MySQL Query to choose all but the most recent datetime

I have a row in my db table that is datetime. How can i write a query to only all rows except one (the most recent).
I would have used
ORDER BY col_name DESC LIMIT 1
if i was choosing only the most recent.. but i actually require all but the most recent.
Thanks
Just select all rows but the first:
ORDER BY col_name DESC LIMIT 1, 18446744073709551615
See 13.2.9. SELECT Syntax which explains the LIMIT clause.
Title says:
MySQL Query to choose all but the most recent datetime
If have duplicated dates you'll have to go for:
select * from t
where val != (select max(val) from t);
This is because if there are 2 max values then limit will only filter the first one and you'll get the other max value in the resultset.

PHP/MySQL Sort By Date

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");

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