Page 1 of 1
Mysql query order by
Posted: Fri Sep 24, 2010 11:48 am
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?
Re: Mysql query order by
Posted: Fri Sep 24, 2010 11:54 am
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
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.
Re: Mysql query order by
Posted: Fri Sep 24, 2010 12:01 pm
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