So, my code looks like this
mysql_query("SELECT * FROM threads WHERE forum_id = '$id' ORDER BY type,posted DESC") or
die(mysql_error());
"posted" is the value of time() and is selected decreased to put the latest one at the top.
"type" contains either 1 or 2. If it's 2, the thread is pinned. Currently, it sorts after posted but those which should be at the top (pinned) are at the bottom. Is there any fix that I'm missing?
Try: ORDER BY type DESC, posted DESC
By default, it sorts ascending. You need to specify the order for both fields you would like to order by.
ORDER BY Documentation
Don't forget that the asc/desc in an order by applies to each individual field, not the entire order by clause.
ORDER BY type DESC, posted ASC
MySQL can also accept arbitrary logic for order by, so for more complicated sort requirements, you could have something like
ORDER BY IF(type=2, 0, 1) AS pinned ASC, posted DESC
as long the arbitrary logic returns something that's trivially sortable (e.g. a number or a string), there's no limit to how complicated the sorting can be.
Related
I want to get data from my database and present each field in separate divs - which I can do. However it is ordered earliest to latest meaning the first bits of data are at the top. How do I get it the other way round? Is it something I have to do in phpMyAdmin?
I am a Noob, please help. (thanks in advance).
Without seeing your actual SQL statements and tables its hard to give a definitive answer.
However, you're looking for the ORDER BY clause. You can order something by a field in either Ascending (1, 2, 3) or Descending (3, 2, 1) Order.
For example:
SELECT * FROM Employees ORDER BY HireDate ASC
vs
SELECT * FROM Employees ORDER BY HireDate DESC
To get it in reverse order.
From what I have understood is that you want to display the data in descending order. Use ORDER BY clause, which helps you to sort the data either in ascending or descending order.
for example:
SELECT * FROM shop
ORDER BY date DESC;
I got an odd problem. Whenever I add a new entry to the database it gives it a higher id number, but somehow sees it as a lower number and puts it below the older ones.
And when sorting DESC in PHP I also get this order, does anybody know whats going wrong here?
I use $res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");to sort them, and it gives the same order as in the pic. (Not sure why i'm being downvoted here but ok..)
Pic:
Your query is:
SELECT * FROM data ORDER BY 'id' DESC
You are sorting by the string 'id', note the syntax highlighting when not within quotes. This means you get them in a random order. Remove the '. If you meant to escape the column id you should use back-ticks:
SELECT * FROM data ORDER BY `id` DESC
When you insert data on the tables, it does not mean that the new number (or the highest) always on the lowest row. It randomly inserts the record. The only way you can sort it when you retrieve the rows in by using ORDER BY clause, example
SELECT *
FROM tableName
ORDER BY ID DESC
So assume that ID is numeric. If you're ID is stored as string then you should convert it to numeric,
SELECT *
FROM tableName
ORDER BY CAST(ID AS SIGNED) DESC
UPDATE 1
It should be
$res = mysql_query("SELECT * FROM data ORDER BY `id` DESC");
not
$res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");
what you have done was you have surrounded the ID with single quote forcing the server to read it as String and not Numeric
When you are not using any ORDER BY clause, the order in PHPMyAdmin is kind of random. Indeed, new rows could take place of old ones.
I am curious how you sort DESC in PHP though.
Don't absolutely trust in GUI web interface because sometimes (not always) it bugs with session management, however you can run SQL Queries using it.
1- To run a SQL query, click on "SQL" on the navigation bar.
2- Enter your SQL in the box provided.
SELECT *
FROM tableName
ORDER BY ID DESC
3- Click "Go".
I have a column which holds status of applications - (New/Approved/Declined/Pending)
The column name is status. Now how do I order the select statement to order status so that 'New' applications come to the top of the display.
I tried this (SELECT * FROM applications ORDER BY status where status ='New')
This does not work, it is giving me error message.
Given status values "archived", "new" and "old" (for which neither ASC or DESC are working) and you want to retrieve all rows, "new" ones first, use this:
SELECT * FROM `applications`
ORDER BY IF(`status` = "new", 0, 1)
Try this:
SELECT * FROM applications ORDER BY status ASC;
If all you have is 'New' and 'Old', then this will result in 'New' first.
If you ONLY want New orders then you don't need an ORDER BY:
SELECT * FROM applications WHERE `status` = 'New';
If there are all kinds of values, like New/Approved/Declined/Pending and you just want to make sure 'New' is at the top you can do this
SELECT * FROM applications ORDER BY `status`, FIELD(`status`,'New');
What if you want 'New' first, then 'Approved', then you don't care what?
SELECT * FROM applications ORDER BY `status`, FIELD(`status`,'New','Approved');
(ASC and DESC have no effect after FIELD, but DESC after status will put your favorite values at the bottom rather than the top)
What about reversing their order but keeping them at the top? Either change their order in the FIELD() function or see below.
Finally, contrary to the previous suggestion, this does not really work:
SELECT * FROM applications ORDER BY FIELD(`status`,'New','Approved'),`status`;
To fix it, you need DESC after FIELD, but it gives you your values ordered in reverse (i.e. 'Approved' first, then 'New', then the rest):
SELECT * FROM applications ORDER BY FIELD(`status`,'New','Approved') DESC,`status`;
I think I spent too much time on this answer. Hmmm.
ugly but
(SELECT * FROM applications where status ='New')
union all
(SELECT * FROM applications where status !='New')
If you want to use this for something serious, replace the status column with a foreign key and add another table for the textual representations of your status_ids.
Then you can sort using
SELECT * FROM applications ORDER BY status_id
Try to avoid using reserved names for columns. It is possible to use them (with backticks), but can easily lead to problems if you don't take care.
I have followings 3 values that could be in a row in database - ON, OFF, SOLD (column sort_it). When I set the sort clausule on ORDER BY sort_it ASC, so I will get the items with a value in the sort_in column OF, then ON and SOLD.
But I need the sequence ON, OFF, SOLD.
Exist any way to do it somehow? I mean... edit a way saving data into database will be demanding, so I would do this in the last moment.
Yes you can use custom data sortings like this:
SELECT * FROM table ORDER BY FIELD(`sort_it`,'ON','OFF','SOLD'),`sort_it`
You can use a CASE statement to generate your custom ordering sequence from the underlying values, something like this:
ORDER BY
CASE sort_it
WHEN 'ON' then 1
WHEN 'OFF' then 2
WHEN 'SOLD' then 3
END
Sample Demo: http://sqlize.com/MGz6lLb0Qk
Using Strings is generally a bad idea. it would be better to use a numeric type. Then you can say ON=1, OFF=2 and SOLD=3 and then sort.
SELECT t.*, IF(sort_it='ON',1,IF(sort_it='OFF',2,3)) as new_sort FROM Table AS t ORDER by new_sort ASC
Another solution from comments on MySql manual:
http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
select * from tablename order by priority='High' DESC, priority='Medium' DESC, priority='Low" DESC;
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.