SQL查询(这个问题我都不知道怎么一句说完,就只有这样写了,各位大神见谅)

有如下一张表:

id            userId           state

1              1                      1

2              1                      2

3              2                      1

4              2                      1

5              3                      2

6              3                      2

 

现在要查出所有state全部为1的userId,该怎么写?

state既有1也有2的呢?

求指教啊,这个问题困扰我两天了,本来以为可以绕过去,结果发现还是不行,只有上来求教了

 

之前这个写错了,【现在要查出所有state全部为1的userId】 只要为1就行, 上边的sql 只能有一条为1的。

select distinct useId from aaaa a where state=1 and (select count(userId) from aaaa b where a.userId=b.userId group by b.userId where b.state!=1) = 0

(select count(userId) from aaaa b where a.userId=b.userId group by b.userId where b.state!=1) 表示查出某userId state不为1的 如果这个数=0 就表示全部为1

select useId from aaaa a where state=1 and exists(select 1 from aaaa b where a.userId=b.userId group by b.userId having count(*) = 1)