Martti Laine
Martti Laine

Reputation: 12985

Order mysql-query alphabetically, a string is given for a number?

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!

Upvotes: 0

Views: 277

Answers (2)

Icarus
Icarus

Reputation: 63956

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.

Upvotes: 0

Chris
Chris

Reputation: 684

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...

Upvotes: 2

Related Questions