0
Table 1 :

ID  City             State
1   NewYork          NY
2   Oklahama         OK
3   california       CA
4   new jersey       NJ
5   Las Vegas        LA

Table 2 :

ID  City 
1    NewYork          
2    NewYork          
3    NewYork          
4    Oklahama
5    Oklahama

NewYork is 3 times and Oklahama is 2 times in table 2. So I want to fetch City List from Table 1 which Cities are used less then 5 times in Table 2

So what will exact query in Mysql?

I am using below code :

select *
from  Table1
where Table1.city in
    (select Table2 .city,count(*)
     from Table2
     having count(*) < 5
     group by Table2.city )
1
  • I was looking for Query So By Mistake i wrote Jquery. Please vote my Question. Commented Jun 26, 2016 at 18:34

2 Answers 2

1

You can use a in clause with a subselect

    select  * from  table1
    where city in (select  city from table2 having count(*) < 5 group by city)

In your code you have a space between the Table2 and .city

select  * 
from  Table1  where Table1.city in   (select  
              Table2 .city,count(*) from Table2 having count(*) < 5 group by Table2.city )

must be

select  * 
from  Table1  
where Table1.city in   (select  Table2.city
                        from Table2 
                         group by Table2.city
                         having count(*) < 5   )

no space between tablename and column ..

you can seee http://sqlfiddle.com/#!9/556cb6/10

Sign up to request clarification or add additional context in comments.

9 Comments

Its not worked for me.I am comparing city from table 1 to Table 2.I want city list from table 1 which is used in table 2 less then 5 times.
I have update the answer ..looking the sample provided you question was not so clear .. l
I checked this it is showing me error on group by clause.Just to be clear again I want to fetch City from table one which city is another table less then 5 times.Lets say NewYork is in table one.and in table two there are four row which contains NewYork 3 times.So i want data from table one which is less then 5 in table 2.Thanks.
You can show me the error message please ...i have update the answer removing distinct (not needed)
I am getting this error: Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group by city'
|
1

How about

select Table1.city
from Table1 inner join Table2 on Table1.city = Table2.city
group by Table1.city
having count(Table2.city) < 5

SQLFiddle

1 Comment

Thank you so much @Tony.This worked for me.This is actually what i want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.