Jump to content

Keep SQL query order from OR statement


Zeradin

Recommended Posts

I have a query that looks like this:

 

SELECT * FROM table WHERE (zip = "foo" OR zip = 94105 OR zip = 94106 OR zip = 94150 OR zip = 94152 OR zip = 94163 OR zip = 94177 OR zip = 94104 OR zip = 94162 OR zip = 94126 OR zip = 94151 OR zip = 94138 OR zip = 94156 OR zip = 94145 OR zip = 94108 OR zip = 94120 OR zip = 94137 OR zip = 94139 OR zip = 94111 OR zip = 94161 ) AND `visible` = 1 AND state = "CA"

 

and I want it to output the results that way, but it outputs some of the 94105 then some 94104 then more 94105 then 94108

 

Is there a way to do this?

Link to comment
Share on other sites

SELECT * FROM table WHERE zip IN ("foo",94105,94106,94150...) AND `visible` = 1 AND state = "CA" ORDER BY zip ASC

 

or perhaps

 

(SELECT * FROM table WHERE zip = "foo" AND `visible` = 1 AND state = "CA")
UNION
(SELECT * FROM table WHERE zip IN (94105,94106,94150...) AND `visible` = 1 AND state = "CA" ORDER BY zip ASC)

Link to comment
Share on other sites

Maybe I'm not explaining this properly. There's nothing in the table that will show the order. have an array of zip codes in what is essentially a random order (from the perspective of the table) and I add them to the SQL query in that order, hoping that it will select them in that order, but it doesn't. It's like:

 

I have this zipcode: 94105

i get a list of zip codes within 5 miles of it

I say SELECT * FROM table WHERE zip_code is "whatever" [OR loop through array to add zips in order]

 

Link to comment
Share on other sites

Well? If you can put them in order in WHERE clause, you can also put them in order into ORDER BY FIELD()

 

SELECT * FROM table WHERE zip IN ("foo",94105,94106,94150...) AND `visible` = 1 AND state = "CA" ORDER BY FIELD(zip,"foo",94105,94106,94150...) ASC

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.