MySQL How to get results based on the order of parameters in the WHERE Clause
I have the following query statement:
SELECT idelm_na AS ID, nd.lat_nd AS lat, nd.lon_nd AS 'lon' , adr.road_adr AS 'road' FROM node_nd nd, node_address_na na, address_adr adr WHERE ((ROUND(lat_nd,6)=ROUND(14.654733,6) AND ROUND(lon_nd,6)=ROUND(121.058403,6)) OR (ROUND(lat_nd,6)=ROUND(14.654791,6) AND ROUND(lon_nd,6)=ROUND(121.062386,6)) OR (ROUND(lat_nd,6)=ROUND(14.654791,6) AND ROUND(lon_nd,6)=ROUND(121.064343,6)) OR (ROUND(lat_nd,6)=ROUND(14.654754,6) AND ROUND(lon_nd,6)=ROUND(121.064403,6)) OR (ROUND(lat_nd,6)=ROUND(14.654648,6) AND ROUND(lon_nd,6)=ROUND(121.06445,6)) OR (ROUND(lat_nd,6)=ROUND(14.653869,6) AND ROUND(lon_nd,6)=ROUND(121.064798,6)) OR (ROUND(lat_nd,6)=ROUND(14.653865,6) AND ROUND(lon_nd,6)=ROUND(121.065399,6)) OR (ROUND(lat_nd,6)=ROUND(14.653880,6) AND ROUND(lon_nd,6)=ROUND(121.066532,6))) AND na.idelm_na = nd.idelm_nd AND adr.id_adr = na.idadr_na;
What it does is that it returns the adr.road_adr associated to the coordinates(lat,lon). What it returns is ordered by idelm_na by default. Is there a way to rewrite this code that will return the result based on the order of the OR argu开发者_运维知识库ments/parameters? I can use UNION ALL with individual SELECT statements, but I think this is too slow. I hope someone can help me here. Thanks!
First, do not use the comma-separated syntax for Joins. Use the ISO standard. Second, to achieve what you want, you need to build the query differently. You can achieve what you want if you supply a sort order to the inputs. In addition to providing the ability to do your sort, you also make it easier to build the list of inputs:
Select idelm_na AS ID, nd.lat_nd AS lat, nd.lon_nd AS 'lon' , adr.road_adr AS 'road'
From node_nd As ND
Join node_address As NA
On NA.idelm_nd = ND.idelm_na
Join address_adr As ADR
On ADR.id_adr = NA.idadr_na
Join (
Select 1 As Rnk, 14.654733 As Lat, 121.058403 As Lon
Union All Select 2, 14.654791, 121.062386
Union All Select 3, 14.654791, 121.064343
Union All Select 4, 14.654754, 121.064403
Union All Select 5, 14.654648, 121.064450
Union All Select 6, 14.653869, 121.064798
Union All Select 7, 14.653865, 121.065399
Union All Select 8, 14.653880, 121.066532
) As Z
On Round(lat_nd, 6) = Z.Lat
And Round(lon_nd, 6) = Z.Lon
Order By Z.Rnk
You can add an "ORDER BY" clause to the SELECT statement:
SELECT idelm_na AS ID, ... WHERE ... ORDER BY lat_nd, lon_nd;
This will sort the results first by lat_nd, then by lon_nd.
精彩评论