Take the 2-minute tour ×

I need to order rows over their column source. However, here's the table I am querying (simplified):

|id |source |foo  |
|1  |5      |hey  |
|2  |7      |yo   |

And here are the sources:

|id |name   |
|5  |First  |
|7  |Awesome|

Now, if I use a query like this:

SELECT * FROM table ORDER BY source

...the results will order by the id of the source, not the actual name of it. I could simply order the results in PHP, but I'm looking for a sql-solution, if available.

Any help will be appreciated!

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Sounds like you just need to join the tables together, like so:

SELECT * FROM table, sources WHERE table.source = sources.id ORDER BY sources.name

Assuming your sources table is called sources...

share|improve this answer
add comment

I am not sure I quite understand what is it that you find surprising about the way mysql is ordering the results, but if you want the result to be ordered alphabetically, you need to order by name, not by source, because source is an integer.

share|improve this answer
I don't find it surprising, but I simply didn't know the method Chris mentioned. –  Martti Laine Aug 13 '11 at 18:53
It's just an implicit join. You can find more details here en.wikipedia.org/wiki/Join_%28SQL%29 –  nick rulez Aug 13 '11 at 19:28
add comment

Your Answer


