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
https://forums.phpfreaks.com/topic/187615-keep-sql-query-order-from-or-statement/
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)

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]

 

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

Archived

This topic is now archived and is closed to further replies.

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