简体   繁体   中英

MYSQL query on two different columns

I have a table that stores id's, field names and field values. I need to search on two different fields, where the ID's are the same and the field values are taken from two columns using the BETWEEN compare.

Here is a sample of the table:

lid  |  field_name  | field_value
 1   |     lat      |  32.409172
 1   |     lng      | -90.13618300000002
 2   |     lat      |  38.409172
 2   |     lng      | -92.13618300000002

And so on. The idea is to get lid's where lat is between X and Y and lng is between A and B.

You can do a self-join to have latitude and longtitude in one row, then you can apply a where clause as you like:

SELECT lid, lat.field_value AS lat, lng.field_value AS lng
FROM table lat
INNER JOIN table lng
ON lat.lid = lng.lid AND lng.field_name = "lng"
WHERE (lat.field_value BETWEEN x AND y
OR lng.field_falue BETWEEN a AND b)
AND lat.field_name = "lat"

here is all the LIDs with lng between 50 and 60 and lat between 70 and 80. I'm assuming your table is named "table"

select t1.lid
from table t1
join table t2 on t1.lid=t2.lid
where t1.field_name='lng'
and t1.field_value between 50 and 60 
and t2.field_name='lat'
and t2.field_value between 70 and 80 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM