PHP MySQL Order by multiple columns - php

I am looking to create an order based on multiple columns in my table - all date related. For example: my columns are: fee_due, fee_2_due, fee_3_due - they all contains results of various dates. However, I want to create an order combining all columns, so fee_due might be 2012-11-03, fee_2_due might be 2012-11-01 and fee_3_due might be 2012-11-02.
My query needs to be:
SELECT *
FROM table_name
ORDER BY [date] DESC
... whereby the dates from the 3 columns join to form one order, regardless of what column they are in.
Hope that makes sense and thanks in advance.

Additionally you can:
SELECT *
FROM table_name
ORDER BY fee_due ASC,fee_2_due DESC,fee_3_due DESC
You can sort each column independently according to your need.

I used the following to make it work:
SELECT * FROM table ORDER BY camp1 ASC, camp2 ASC, camp3 DESC

Have you try this:
SELECT *
FROM table_name
ORDER BY fee_due,fee_2_due,fee_3_due DESC

Related

Selecting multiple tables and displaying them ordered by datetime column

I want to display the logs to recent activities page ordered by date. Now I was trying to execute this to my mysql
"SELECT * FROM tracking_log.editlog, tracking_log.deletelog, tracking_log.loginlog, tracking_log.logoutlog ORDER BY time ASC";
but it always says
Column 'time' in order clause is ambiguous
all of the tables have a time column, format by datetime (0000-00-00 00:00:00)
How am I going to fetch them ordered by time?
Thanks in advance!
By which table's time column you want to order?
Assuming you want to order the result set by tracking_log.editlog.time column then the query would look like below:
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY tracking_log.editlog.time ASC;
Just in case if all of the time columns in the respective table don't contain NOT NULL values at the same time then you need to use COALESCE I guess.
Query using COALESCE
SELECT
*
FROM tracking_log.editlog, tracking_log.deletelog,
tracking_log.loginlog, tracking_log.logoutlog
ORDER BY
COALESCE(tracking_log.editlog.time , tracking_log.deletelog.time, tracking_log.loginlog.time,tracking_log.logoutlog.time) ASC;
'tracking_log' is your database name, and you're selecting multiple tables from that database, so you need to specify from which table you want to order 'time' by:
select * from tracking_log.editlog, tracking_log.deletelog ORDER BY tracking_log.editlog.time ASC
or whichever table from your database you want to use 'time' from. This will fix the error but won't return any results because you have multiple tables in a SELECT clause without anything relating them together.
You'll need to specify some common columns on which you want to return results rather than getting the wildcard and then UNION the tables to aggregate the results. For example, if you have common columns userID, description and time in all your tables, you could do the following:
(SELECT userID, description, time FROM tracking_log.editlog)
UNION
(SELECT userID, description, time FROM tracking_log.deletelog)
ORDER BY time

Select data from mysql in different order

I have data along with the ids 1,2,3,4,5 but these are not primary ids...
I want to fetch data in order like 4,3,2,1,5.
I cann't change the ids in database.If i use order by desc it will fetch 5,4,3,2,1.
you can use FIELD in order clause
order by FIELD(field_name,4,3,2,1,5)
Order by field is one such way:
select * from TABLE order by FIELD(column_name,4,3,2,1,5) ;
You can look into this for more details:
Field Example
you can use ORDER BY RAND() for random order.
Try this,
SELECT table.* FROM table ORDER BY FIELD(id,4,3,2,1,5);

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

Select Statement By ORDER

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.

How to sort rows by ON, OFF, SOLD

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;

Categories