Dave Vockell
Dave Vockell

Reputation: 43

SQL with Multiple Where Clauses

First -- I have read about 7 pages of posts with similar titles but couldn't find the right insight for my challenge

My SQL:

SELECT name, address, lat, lng, city, state, phone, zip, info
    , ( 3959 * acos( cos( radians('37.4969') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122.2674') ) + sin( radians('37.4969') ) * sin( radians( lat ) ) ) ) AS distance 
FROM myhealthfinder_map 
HAVING distance < '50'  and location = '2'  
ORDER BY distance LIMIT 0 , 10

I get the error message: Invalid query: Unknown column 'location' in 'having clause'

if instead of HAVING I just make it WHERE location = '2' then it works fine [it finds the column] (but I need the distance selector).

Any suggestion on how to knock this down?

Upvotes: 0

Views: 934

Answers (2)

peterm
peterm

Reputation: 92785

Don't use HAVING without GROUP BY. You can try this instead

SELECT name, address, lat, lng, city, state, phone, zip, info, ( 3959 * acos( cos( radians('37.4969') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122.2674') ) + sin( radians('37.4969') ) * sin( radians( lat ) ) ) ) AS distance 
  FROM myhealthfinder_map 
 WHERE location = '2' AND
( 3959 * acos( cos( radians('37.4969') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122.2674') ) + sin( radians('37.4969') ) * sin( radians( lat ) ) ) ) < 50
 ORDER BY distance LIMIT 0 , 10

It's not pretty, but it should work.

Upvotes: 0

Eli Gassert
Eli Gassert

Reputation: 9763

Use both WHERE and HAVING. HAVING is used for aggregated and calculated columns. And WHERE on plain old columns.

SELECT name, address, lat, lng, city, state, phone, zip, info
    , ( 3959 * acos( cos( radians('37.4969') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122.2674') ) + sin( radians('37.4969') ) * sin( radians( lat ) ) ) ) AS distance 
FROM myhealthfinder_map 
WHERE location = '2' 
HAVING distance < '50'  
ORDER BY distance LIMIT 0 , 10

More explanation found here WHERE vs HAVING

Upvotes: 2

Related Questions