SELECT table1.id, (SELECT MIN(SQRT( POW( 69.1 * ( latitude - table1.lat ) ,
2 ) + POW( 69.1 * ( table1.lon - longitude ) * COS( latitude / 57.3 ) , 2 )
)) from table2 limit 1) AS distance FROM table1
The result itself seems correct, however I actually want the query to return table2.id based on the calculated value instead. How can I achieve that?
table1 contains id, lat, lon
table2 contains id, latitude, longitude
I do need to get the smallest distance's ID(table2.id) for each row in table1 using the data in table2.
SELECT table1.id, (SELECT table2.id from table2 order by (SQRT( POW( 69.1 * (
latitude - table1.lat ) , 2 ) + POW( 69.1 * ( table1.lon - longitude ) * COS(
latitude / 57.3 ) , 2 ) )) limit 0,1 ) as table2_id FROM table1
Related
I want to calculate the median and average for given coordinates in a specific radius.
The important attributes are:
- latitude
- longitude
- price
The sql command to calculate the average is:
SELECT avg(price) as average
FROM (SELECT r.*,
( 6371 * acos( cos( radians(37.3541079) ) * cos( radians( ANY_VALUE(`latitude` )) ) * cos( radians( ANY_VALUE(`longitude`) ) - radians(-121.9552356) ) + sin( radians(37.3541079) ) * sin( radians( ANY_VALUE(`latitude`) ) ) ) ) AS distance
FROM `Rental` r
) r
WHERE distance <= 20;
My question is how can I calculate the median for the price in the given coordinates and radius. MySQL has no median() function.
EDIT:
Now I have tried the code from Simple way to calculate median with MySQL
SELECT AVG(middle_values) AS 'median' FROM (
SELECT t1.price AS 'middle_values' FROM
(
SELECT #row:=#row+1 as `row`, x.price
FROM rental AS x, (SELECT #row:=0) AS r
WHERE 1
-- put some where clause here
ORDER BY x.price
) AS t1,
(
SELECT COUNT(*) as 'count'
FROM rental x
WHERE 1
-- put same where clause here
) AS t2
-- the following condition will return 1 record for odd number sets, or 2 records for even number sets.
WHERE t1.row >= t2.count/2 and t1.row <= ((t2.count/2) +1)) AS t3;
It works for all the 200'000 records, but when I will add the WHERE distance <= 20 is the mysql - request overloaded.
SELECT AVG(middle_values) AS 'median' FROM (
SELECT t1.price AS 'middle_values' FROM
(
SELECT #row:=#row+1 as `row`, x.price
FROM rental AS x, (SELECT #row:=0) AS r, (SELECT a.*,
( 6371 * acos( cos( radians(37.3541079) ) * cos( radians( ANY_VALUE(`latitude` )) ) * cos( radians( ANY_VALUE(`longitude`) ) - radians(-121.9552356) ) + sin( radians(37.3541079) ) * sin( radians( ANY_VALUE(`latitude`) ) ) ) ) AS distance
FROM `Rental` a
) a
WHERE distance <= 20
-- put some where clause here
ORDER BY x.price
) AS t1,
(
SELECT COUNT(*) as 'count'
FROM rental x, (SELECT a.*,
( 6371 * acos( cos( radians(37.3541079) ) * cos( radians( ANY_VALUE(`latitude` )) ) * cos( radians( ANY_VALUE(`longitude`) ) - radians(-121.9552356) ) + sin( radians(37.3541079) ) * sin( radians( ANY_VALUE(`latitude`) ) ) ) ) AS distance
FROM `Rental` a
) a
WHERE distance <= 20
-- put same where clause here
) AS t2
-- the following condition will return 1 record for odd number sets, or 2 records for even number sets.
WHERE t1.row >= t2.count/2 and t1.row <= ((t2.count/2) +1)) AS t3;
Is there somewhere a misstep?
The problem is with the table scan to compute the distances, not with the median.
Put the data in a TEMPORARY TABLE so you don't have to evaluate it 3 times (avg, count, and median).
Add a "bounding box" to the innermost WHERE to limit the checks to a 20x20 "square".
INDEX(latitude)
Use HAVING distance < 20 instead of needing yet-another subquery.
A table contains multiple addresses (latitude and longitude) of a dealers but I want to get nearest dealers
Here is query which return works fine with order by and where dealer=1 of a single dealer but I need multiple unique dealers.
check query and first image result
SELECT
*, ROUND(
(
3959 * ACOS(
COS(RADIANS(41.355724)) * COS(
RADIANS(adzip.dealer_zipcode_latitude)
) * COS(
RADIANS(adzip.dealer_zipcode_longitude) - RADIANS(- 87.607332)
) + SIN(RADIANS(41.355724)) * SIN(
RADIANS(adzip.dealer_zipcode_latitude)
)
)
), 2
) AS dealer_distance
FROM
ad_dealers_zipcodes AS adzip
WHERE adzip.dealer_zipcode_dealer_id = 1 #GROUP BY adzip.dealer_zipcode_dealer_id
ORDER BY dealer_distance ASC
when I add group by adzip.dealer_zipcode_dealer_id query returns 4th record but I need the 1st record of result which dealer_distance is 13.80
Actually, I think you should add a level to your query for the group by statement to work as you intend, like this:
SELECT *, min(dealer_distance) AS min_dealer_distance FROM
(
SELECT
*, ROUND(
(
3959 * ACOS(
COS(RADIANS(41.355724)) * COS(
RADIANS(adzip.dealer_zipcode_latitude)
) * COS(
RADIANS(adzip.dealer_zipcode_longitude) - RADIANS(- 87.607332)
) + SIN(RADIANS(41.355724)) * SIN(
RADIANS(adzip.dealer_zipcode_latitude)
)
)
), 2
) AS dealer_distance
FROM
ad_dealers_zipcodes AS adzip
WHERE adzip.dealer_zipcode_dealer_id = 1 #GROUP BY adzip.dealer_zipcode_dealer_id
ORDER BY dealer_distance ASC
) as t1
GROUP BY dealer_zipcode_dealer_id
ORDER BY min_dealer_distance ASC
I have 2 tables
1. feeds => id,name
2. feed_locations => id, feed_id, latitude,longitude,location_name
A feed have multiple locations.
now i want to search near by feed from user current location
I require user latitude or longitude so i fetch from google location and radius
Now i use this mysql query
SELECT
`Feed`.`id`,
`Feed`.`name`,
(3959 * acos (cos ( radians(40.7127837) ) * cos( radians( FeedLocation.latitude ) ) * cos( radians( FeedLocation.longitude ) - radians(-74.00594130000002) ) + sin ( radians(40.7127837) ) * sin( radians( FeedLocation.latitude )))) AS `distance`,
(Select COUNT(id) FROM feed_locations WHERE feed_id = `Feed`.`id`) AS `location_count` FROM `feeds` AS `Feed`
LEFT JOIN `feed_locations` AS `FeedLocation` ON (`FeedLocation`.`feed_id` = `Feed`.`id`)
GROUP BY `Feed`.`id` HAVING distance < 10
ORDER BY `distance` ASC
This query giving me result but
i require minimum distance of the feed_locations from user current location. Distance field give me highest value but i require lowest value from feed_locations table.
My query is working but issue it that :
Like if a single feed have 10 location lik 1m,2m,3m,4m,5m,10m,100m distance. and i want to find 5m distance all feed then it works but it shows me that this feed have 5m. distance from me but result should be 1m distance.
I have created a Fiddle please check http://sqlfiddle.com/#!9/c408e6/5
According to the fiddle in table 1 result is coming that feed1 is 4.02m from my current location but this feed have 2 location in table2 i have show each of location distance .so feed1 one of location is zero mile distance from me but it give result that feed1 is 4.02mile
SELECT
a.id,
a.name,
a.distance,
a.location_count
FROM
(SELECT
`Feed`.`id`,
`Feed`.`name`,
(3959 * acos (cos ( radians(40.7127837) ) *
cos( radians( FeedLocation.latitude ) ) *
cos( radians( FeedLocation.longitude ) -
radians(-74.00594130000002) ) + sin ( radians(40.7127837) ) *
sin( radians( FeedLocation.latitude )))) AS `distance`,
(Select COUNT(id)
FROM feed_locations
WHERE feed_id = `Feed`.`id`) AS `location_count`
FROM `feeds` AS `Feed`
LEFT JOIN `feed_locations` AS `FeedLocation` ON (`FeedLocation`.`feed_id` = `Feed`.`id`)
ORDER BY `distance` ASC) AS a
GROUP BY a.id HAVING distance < 10;
In the fiddle I worked out this query you see and it works, now result is 0. The point is that if you group a not ordered set of records and then you order... you do not order anything. You have to order and then group the ordered set.
Hope it works for you.
Regards
I'm not quite sure how to expand this query so that I can also have a AVG(price_current) column ... instead of having to calculate this value within PHP once the query comes back.
SELECT
listing_subtype, bedrooms, total_baths, tot_sqft_finished, price_current, latitude, longitude, (
3959 * acos (
cos ( radians(48.639) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-123.404) )
+ sin ( radians(48.639) )
* sin( radians( latitude ) )
)
) AS distance
FROM rets_property_resi
WHERE listing_subtype = 'Single Family Detached' AND
bedrooms >= 2 AND bedrooms <= 3 AND
total_baths >= 1 AND total_baths <= 2 AND
tot_sqft_finished >= 2000 AND tot_sqft_finished <= 2500
HAVING distance < 5
ORDER BY distance
LIMIT 0, 25;
I'm going to make some assumptions here:
You look for similar houses/homes in a given radius around a requested one. Each of those homes has a primary key in the table you are querying from. Let us call that primKey here.
Additionally, you want the average price of all returned homes which is limited to 0,25, and not the AVG of all records in the table that match you WHERE clause.
All returned rows will have therefore an extra field with the average price and is the same for each row.
You will have to run the same query again as a subquery. However, since you want to limit the AVG you have to run that in a subquery to calculate the correct AVG.
This is really clunky:
SELECT
rets_property_resi.listing_subtype, rets_property_resi.bedrooms, rets_property_resi.total_baths, rets_property_resi.tot_sqft_finished, rets_property_resi.price_current, rets_property_resi.latitude, rets_property_resi.longitude, (
3959 * acos (
cos ( radians(48.639) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-123.404) )
+ sin ( radians(48.639) )
* sin( radians( latitude ) )
)
) AS distance, outerSubQuery.averagePrice
FROM rets_property_resi
LEFT JOIN
(
SELECT innerSubQuery.primKey AS primKey, AVG(innerSubQuery.price_current) AS averagePrice
FROM
(SELECT
primKey, price_current, (
3959 * acos (
cos ( radians(48.639) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-123.404) )
+ sin ( radians(48.639) )
* sin( radians( latitude ) )
)
) AS distance
FROM rets_property_resi
WHERE listing_subtype = 'Single Family Detached' AND
bedrooms >= 2 AND bedrooms <= 3 AND
total_baths >= 1 AND total_baths <= 2 AND
tot_sqft_finished >= 2000 AND tot_sqft_finished <= 2500
HAVING distance < 5
ORDER BY distance
LIMIT 0, 25) AS innerSubQuery
GROUP BY innerSubQuery.primKey
) AS outerSubQuery ON (outerSubQuery.primKey = rets_property_resi.primKey)
WHERE listing_subtype = 'Single Family Detached' AND
bedrooms >= 2 AND bedrooms <= 3 AND
total_baths >= 1 AND total_baths <= 2 AND
tot_sqft_finished >= 2000 AND tot_sqft_finished <= 2500
HAVING distance < 5
ORDER BY distance
LIMIT 0, 25;
I bet there is a more elegant version of this though. You might be better off with a temporary table here or keep just calculating in code.
The following query works for me. However, is there a way to speed it up (table1/2 contain each more than 300000 entries). I also would like to query more data in the subquery and use the distance just to filter results. The two tables have not much in common except the lat/lon.
SELECT `lat1`,
`lon1`,
(SELECT Sqrt(Pow( 69.1 * ( `lat1` - `lat2` ), 2 )
+ Pow( 69.1 * ( `lon2` - `lon1` ) * Cos( `lat` / 57.3 ), 2 )
) AS
distance
FROM table1
ORDER BY distance
LIMIT 0, 1) AS `test`
FROM `table2`
Thanks in advance