Yev
Yev

Reputation: 2081

Choose which result comes first in MySQL result set

I'm pulling a list of counties and need to be able to specify which one will go first in the result set depending on the url. The remaining counties can be in whatever order. I don't know the county ids beforehand I just know that they are in a specific state. For example:

nj/county/bergen

should pull up

Bergen

Passaic

Essex

Morris

Sussex

Hudson

Union

etc


nj/county/morris

should pull up

Morris

Passaic

Essex

Bergen

Sussex

Hudson

Union

etc

and so on, and so forth.

Upvotes: 1

Views: 71

Answers (1)

Matthew
Matthew

Reputation: 9949

EDIT 2 Removed earlier answers as they add little value.

Debugged query:

SELECT * from counties ORDER BY county like 'Essex' DESC, county ASC

Reason this works: The county like 'Essex' evaluates to true/false or more specifically: 1 or 0. I sort these descending and the matches (1's) will be on top, anything that doesn't match (0's) is on bottom. The second ORDER BY field just ensures the rest of the list is in alphabetical order.

SQL Fiddle: http://sqlfiddle.com/#!2/a6a738/5

For posterity here is the table I used:

CREATE TABLE counties 
(
 id int auto_increment primary key, 
 county varchar(20)
);

INSERT INTO counties
(county)
VALUES
('Bergen'),('Passaic'),('Essex'),('Morris'),('Sussex'),('Hudson');

Upvotes: 1

Related Questions