vipul sharma vipul sharma - 2 months ago 5
MySQL Question

How to use having with or condition in mysql?

I have two similler queries with same table name which are working fine individually. But I want to merge them with condition ((city_id = 1 and country_id = 1) or distance < "20")

First query

select id , lat , long , city_id , country_id
from element_table
where city_id = 1 and country_id = 1 and id < 20


Second query
Here I am using search with lat lon

select id , lat , long , city_id , country_id ,
my_distance_calculationformula_with_lat_long as distance
from element_table where id < 20 having distance = "20"

Answer

you can use where and having

select id , lat , long , city_id , country_id ,
my_distance_calculationformula_with_lat_long as distance  
from element_table
where city_id = 1 and country_id = 1 and id < 20 
having distance = 20

in you case (your comment) Then you should not use an alias and perform only the where

select id , lat , long , city_id , country_id ,
my_distance_calculationformula_with_lat_long as distance  
from element_table
where city_id = 1 and country_id = 1 and id < 20 
or   my_distance_calculationformula_with_lat_long < 20

(and if your my_distance_calculationformula_with_lat_long is a long sql code . you should repeat the code for not using alias ..column alias in not allowed in where)

Comments