Mysql query order by

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
carcaix
Forum Newbie
Posts: 12
Joined: Sun Aug 29, 2010 9:33 am

Mysql query order by

Post by carcaix »

I have this query:

$result = mysql_quey(SELECT users, points FROM registered ORDER BY points DESC, id ASC);

Althought the id field isn't selected in the query, it's correct to call it in the ORDER BY property? In other words, in a ORDER BY query it's possible to use fields that you haven't selected but are in the same table, and if they are in another one how can i do that?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Mysql query order by

Post by John Cartwright »

carcaix wrote:in a ORDER BY query it's possible to use fields that you haven't selected but are in the same table,
Yes, it's possible. You can reference any columns in the table(s) your querying against. Trying things out for yourself though won't hurt anyone, I promise :D
carcaix wrote:and if they are in another one how can i do that?
You would need to join the tables together based on its primary/foreign key (ideally), then reference the columns them normally as before.
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Re: Mysql query order by

Post by thiscatis »

carcaix wrote:I have this query:

$result = mysql_quey(SELECT users, points FROM registered ORDER BY points DESC, id ASC);

Althought the id field isn't selected in the query, it's correct to call it in the ORDER BY property? In other words, in a ORDER BY query it's possible to use fields that you haven't selected but are in the same table, and if they are in another one how can i do that?
I think the FROM statement is the first part that's being executed in a query.
The select is just at the end when the fields that have been returned from db are being selected.
So it's possible if they are in the same table.

If they're in a different table you can try something like:
SELECT u.user, u.points, t.field, t.field2
FROM users as u, table as t
WHERE u.user = t.field
ORDER BY t.otherfield
Post Reply