从表2中的表1列计数中获取数据

时间:2016-06-26 18:30:00

标签: mysql sql inner-join

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是3次,Oklahama是表2中的2次。 所以我想从表1中获取城市列表,其中城市在表2中的使用次数少于5次

那么Mysql中的确切查询是什么?

我正在使用以下代码:

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

2 个答案:

答案 0 :(得分:1)

您可以将in子句与子选择

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

在代码中,Table2和.city之间有一个空格

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

必须是

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

tablename和column之间没有空格..

你可以看到http://sqlfiddle.com/#!9/556cb6/10

答案 1 :(得分:1)

怎么样

l = [0,1,0,1]
f = map(lambda x: int(not x),l)
print f # prints [1,0,1,0]

SQLFiddle