I'm trying to select events in a 5 km radius and order them by likes and from oldest to newest. I know how to select events and order them by likes, but I can't figure this one out. The problem maybe is that the location is stored in a different table.
Database structure:
event plusone (like) location
id_event id_plusone id_location
location_id event_id lat
... user_id lon
... city_id
full_name
....
The SQL statement I'm trying:
SELECT 3956 * 2 * ASIN(
SQRT(POWER(SIN((50.127946 - abs(l.lat)) * pi()/180 / 2),2) + COS(50.127946 * pi()/180 ) *
COS(abs(l.lat) * pi()/180) * POWER(SIN((14.4882912 - l.lon) * pi()/180 / 2), 2) )) AS distance,e.*,COUNT( p.id_plusone ) AS
likes
FROM
event e,location l
LEFT JOIN plusone p ON p.event_id = e.id_event
WHERE
e.location_id = l.id_location AND distance<=5 GROUP BY e.id_event
ORDER BY e.timestamp DESC,likes DESC
The huge column at the beginning is calculation of distance of the event from user position using latitude and longitude.
This is what I get from the SQL debugger:
#1054 - Unknown column 'distance' in 'where clause'
Does anybody know how to do this?
Is hard to track where the error is, you should try to solve the distance part first.
SELECT
event_id,
3956 * 2 * ASIN(SQRT( POWER(SIN((50.127946 - abs(l.lat)) * pi()/180 / 2),2)
+ COS(50.127946 * pi()/180 ) * COS(abs(l.lat) * pi()/180) * POWER(SIN((14.4882912 – l.lon) * pi()/180 / 2), 2) )) AS distance,
FROM event e
JOIN location l
WHERE distance <= 5
And then join to back to the event table
SELECT e.*, count(p.id_plusone)
FROM event e
LEFT JOIN plusone p
ON p.event_id = e.id_event
JOIN ( Previous Distance Query) d
ON e.event_id = d.event_id
GROUP BY e.id_event
ORDER BY e.timestamp DESC, likes DESC
and btw, this group_by will bring you event_id plus random values for e.* so be carefull
$latitudeD= latitude;
$longitudeD = longitude;
SELECT event,
SQRT(
POW(69.1 * (coordX - $latitudeD), 2) +
POW(69.1 * ($longitudeD - coordY) * COS(coordX / 57.3), 2)) AS distance
FROM db.table WHERE SQRT(
POW(69.1 * (coordX - $latitudeD), 2) +
POW(69.1 * ($longitudeD - coordY) * COS(coordX / 57.3), 2)) < 50 ORDER BY distance
;
Related
SELECT id,businessName,GROUP_CONCAT(id) FROM tbl_business LIMIT 0,1
Above query is giving me below results
1 Camp San Fransisco 1,4
Now if i apply GROUP BY and limit on same query, GROUP_CONCAT column is not giving me same results as before.
SELECT id,businessName,GROUP_CONCAT(id) FROM tbl_business GROUP BY id LIMIT 0,1
Query Results
1 Camp San Fransisco 1
I'm using GROUP BY id for fetching a unique records with some where condition.
Is there are any alternatives for using GROUP_BY with GROUP_CONCAT or any other methods for MySQL which can be usefull here.
I want to preserve first query results with id so i just have to call second query based on first results id if it is possible. I can not remove GROUP BY id because of multiple table's LEFT JOIN and some SUB QUERY are depends on it
Above queries are just for explanation purpose , original query is much longer.
Actual Query :
SELECT bs.id,bs.businessName,bs.businessDesc,bs.latitude,bs.longitude,bs.slug,bs.contactNo,bs.location,bs.isAddedBy,bs.createdDate,cat.categoryName as category,GROUP_CONCAT(DISTINCT(bcat.categoryName) SEPARATOR ', ') as subcategory,
(SELECT COUNT(id) FROM tbl_reviews WHERE referenceId = bs.id) as totalReview,
(SELECT CEIL(AVG(rating)) FROM tbl_reviews WHERE referenceId = bs.id) as avgRating,
(SELECT imageName FROM tbl_business_images as bimg WHERE bimg.businessId = bs.id LIMIT 1) as bImage,
(
(ACOS
(
SIN(37.09024 * PI() / 180) * SIN(bs.latitude * PI() / 180) + COS(37.09024 * PI() / 180) * COS(bs.latitude * PI() / 180) * COS(
(-95.712891 - bs.longitude) * PI() / 180)
)* 180 / PI()
) * 60 * 1.1515 * 1.609344
) as distance,
(SELECT
(DATEDIFF(bs.createdDate,NOW()) * 5) +
((SELECT COUNT(id) FROM tbl_business_images WHERE businessId = bs.id) * 2) +
((SELECT count(id) FROM tbl_business_views WHERE businessId = bs.id) * 2) +
((SELECT COUNT(id) FROM tbl_reviews WHERE referenceId = bs.id) * 10))
as totalPoint
FROM tbl_business as bs
LEFT JOIN tbl_category as cat
ON bs.businessCat = cat.id
LEFT JOIN tbl_business_subcategories as bsubs
ON bs.id = bsubs.businessId
LEFT JOIN tbl_category as bcat
ON bsubs.subcategoryId = bcat.id
WHERE bs.isActive = 'y'
GROUP BY bs.slug
Current Query Output :
id businessName businessDesc latitude longitude slug contactNo location isAddedBy createdDate category subcategory totalReview avgRating bImage distance totalPoint
1 test test 45.14 -122.82 test 1234567890 USA c 2018-09-29 11:38:58 Category Subcategory1,subcategory2 1 5 image.png 2382.763331498852 -4
Any help is appreciated.
this is Lat and Lon example in mysql database
ID | Lat | Lon
1 | 3.1412 | 101.6865
2 | 1.2897 | 103.8501
The formula below calculates the distance between two Lat (latitudes) and Lon (longitudes) and gets the result that I want. But this formula doesn't extract my Lat and Lon from the database. I would like to ask, how to get the distance result by using ID and calculate two Lat and Lon? My friend told me using Join table, but I still don't get the answer..
SELECT ROUND(6353 * 2 * ASIN(SQRT( POWER(SIN((3.1412 -
abs(1.2897)) * pi()/180 / 2),2) + COS(3.1412 * pi()/180 ) * COS(
abs(1.2897) * pi()/180) * POWER(SIN((101.6865 - 103.8501) * pi()/180 / 2), 2) )), 2);
Thanks for advance
You can join the same table two time one for Id 1 and one for id 2 assigning different alias name
then use the related column name
SELECT ROUND(6353 * 2 * ASIN(SQRT( POWER(SIN((a.lat -
abs(b.lat)) * pi()/180 / 2),2) + COS(a.lat * pi()/180 ) * COS(
abs(b.lat) * pi()/180) * POWER(SIN((a.lng - b.lng) * pi()/180 / 2), 2) )), 2);
from my_table a
inner join my_table b on a.id = 1 and b.id = 2
It is working for me
SELECT *,(((acos(sin((12.942999*pi()/180)) * sin((`Lat`*pi()/180))+cos((12.942999*pi()/180)) * cos((`Lat`*pi()/180)) * cos(((74.82994- `Lon`)* pi()/180))))*180/pi())*60*1.1515*1.609344 ) as distance FROM ven_vendor HAVING distance <= 10
I'm attempting to assign the closest location to a community based on the community postcode and using the Haversine formula with SQL described here. I need to return a single scalar value but I can't seem to avoid having the second calculated distance value which is needed to determine the closest location. Help.
UPDATE Community AS c
JOIN Postcode p on p.id = c.postcode_id
JOIN (
SELECT 100.0 AS radius, 111.045 AS distance_unit
) AS a
SET c.location_id = (
SELECT l.id,
a.distance_unit
* DEGREES(ACOS(COS(RADIANS(p.latitude))
* COS(RADIANS(l.latitude))
* COS(RADIANS(p.longitude - l.longitude))
+ SIN(RADIANS(p.latitude))
* SIN(RADIANS(l.latitude)))) AS distance
FROM Location AS l
WHERE l.latitude
BETWEEN p.latitude - (a.radius / a.distance_unit)
AND p.latitude + (a.radius / a.distance_unit)
AND l.longitude
BETWEEN p.longitude - (a.radius / (a.distance_unit * COS(RADIANS(p.latitude))))
AND p.longitude + (a.radius / (a.distance_unit * COS(RADIANS(p.latitude))))
HAVING distance <= a.radius
ORDER BY distance
LIMIT 1
)
Using the structure you have, you need to move the distance calculation into the WHERE and ORDER BY clauses:
SET c.location_id = (
SELECT l.id
FROM Location AS l
WHERE l.latitude
BETWEEN p.latitude - (a.radius / a.distance_unit)
AND p.latitude + (a.radius / a.distance_unit)
AND l.longitude
BETWEEN p.longitude - (a.radius / (a.distance_unit * COS(RADIANS(p.latitude))))
AND p.longitude + (a.radius / (a.distance_unit * COS(RADIANS(p.latitude))))
AND a.distance_unit
* DEGREES(ACOS(COS(RADIANS(p.latitude))
* COS(RADIANS(l.latitude))
* COS(RADIANS(p.longitude - l.longitude))
+ SIN(RADIANS(p.latitude))
* SIN(RADIANS(l.latitude)))) <= a.radius
ORDER BY a.distance_unit
* DEGREES(ACOS(COS(RADIANS(p.latitude))
* COS(RADIANS(l.latitude))
* COS(RADIANS(p.longitude - l.longitude))
+ SIN(RADIANS(p.latitude))
* SIN(RADIANS(l.latitude))))
LIMIT 1
)
I am trying to count of coupons sold by each store from the list of stores within 20 miles range. I know the following syntax will work if there is only 1 store.
SELECT sum(couponscount) as count where restaurant IN (SELECT storename where bhal bhal bhal and output is one value)
What is I the IN (SELECTstorenamewhere bhal bhal bhal and output is multiple values) will return multiple values?
Like in my case the complete SQL is like and its not working
SELECT sum(couponscount) as count FROM `coupons` having `restaurant` IN (SELECT `storename`, ((ACOS(SIN(-27.561264299999998 * PI()/180) * SIN(latitude * PI()/180) + COS(-27.561264299999998 * PI()/180) * COS(latitude * PI()/180) * COS((153.07304890000003 – longitude) * PI()/180)) *180 / PI( )) *60 * 1.1515) AS `distance` FROM `stores` WHERE `status`=’active’ HAVING `distance` <=20)
Is there anyway to make it working?
SELECT sum(couponscount) AS COUNT,restaurant
FROM `coupons`
WHERE `restaurant` IN
(SELECT `storename`
FROM `stores`
WHERE `status`='active'
AND
((ACOS(SIN(-27.561264299999998 * PI()/180) * SIN(latitude * PI()/180) + COS(-27.561264299999998 * PI()/180) * COS(latitude * PI()/180) * COS((153.07304890000003 – longitude) * PI()/180)) *180 / PI()) *60 * 1.1515) <=20)
GROUP BY restaurant
Also use proper quotes for active.
Presumably, you want to get the count of coupons from stores within a distance of 20. Moving the having condition to a where clause should do what you want:
SELECT sum(couponscount) as count
FROM `coupons`
WHERE `restaurant` IN (SELECT `storename`
FROM `stores`
WHERE `status` = 'active' AND
((ACOS(SIN(-27.561264299999998 * PI()/180) * SIN(latitude * PI()/180) + COS(-27.561264299999998 * PI()/180) * COS(latitude * PI()/180) * COS((153.07304890000003 – longitude) * PI()/180)) *180 / PI( )) *60 * 1.1515) <= 20
);
You had a major syntax problem because your subquery returned two columns. When you use a subquery with in, you can only return one column, in this case, storename. I moved the code for the distance calculation to the where clause. No having clause is needed either in the subquery or the outer query.
I have the next query for getting addresses within a given distance and given postal code. Distance is calculated, based upon longitude and latitude data.
In this example i have replaced the user-input for just values (lat=52.64, long=6.88 en desired distance=10km)
the query:
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2) + POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses distance
WHERE distance < 10
ORDER BY `distance` DESC
gives unknown column distance as error message.
when leaving out the where clausule i get every record of the table including their calculated distance. In this case i have to fetch the whole table.
How do i get only the desired records to fetch??
Thanks in advance for any comment!
You can't reference an alias in the select clause from another part of the sql statement. You need to put the whole expression in your where clause:
WHERE
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2)
+ POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) < 10
A cleaner solution would be to use a sub-query to generate the calculated data:
SELECT *, distance
FROM (
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2)
+ POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses
) d
WHERE d.distance < 10
ORDER BY d.distance DESC
Demo: http://www.sqlize.com/q96p2mCwnJ
As mellamokb notes, you can't reference column aliases in the WHERE clause. You can, however, do it in a HAVING clause:
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2) +
POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses
HAVING distance < 10
ORDER BY distance DESC
Ps. If you have lots of addresses, you might want to consider optimizing the query by ruling out some of them early. For example, with suitable indexes, the following version might be considerably faster:
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2) +
POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses
WHERE latitude > '52.64' - 10 / (69.1/1.61)
AND latitude < '52.64' + 10 / (69.1/1.61)
AND longitude > '6.88' - 10 / (53/1.61)
AND longitude < '6.88' + 10 / (53/1.61)
HAVING distance < 10
ORDER BY distance DESC
You are aliasing the calculation as 'distance', but you are also aliasing table 'lp_relations_addresses' as 'distance'. Try giving them a different name like this:
SELECT *,
ROUND( SQRT( POW( ( (69.1/1.61) * ('52.64' - latitude)), 2) + POW(( (53/1.61) * ('6.88' - longitude)), 2)), 1) AS distance
FROM lp_relations_addresses addr
WHERE distance < 10
ORDER BY `distance` DESC