sql查询问题,请大家帮帮忙,谢谢了

有两列数据,数据结构如下
用户号 类型
a 1
b 1
b 2
c 1
c 2
c 3
d 1
d 2
e 2
e 3
f 3
我想查询类型只是1的用户号,或者类型只是1,2的用户号,或者类型同时为1,2,3的用户号
谢谢大家

可以像下面这样,统计一下每个用户不同类型的数量,限定类型数量和类型值来过滤
 select * from 表名 a,(select count(distinct *)  cnt,用户号 from 表名 group by 用户号) b 
 where  a.用户号=b.用户号 and ( (a.类型=1 and cnt=1) or  (cnt=3)  or (cnt=2 and a.类型<>3)

建议你分别查询出这三个表然后union成最终表。

    select  a.*,b.*,c.* from   (select table.yhh from table  where table.lx=1) a (select table.yhh from table  where 

    table.lx=2) b  (select table.yhh from table  where table.lx=3) c where a.yhh=b.yhh or (a.hh=b.yhh and 

     a.yhh=c.yhh);

table是你的表,yhh是用户号字段,lx是类型字段。你试试这个能不能查出你想要的结果,我这边没有数据库验证不了

给你的上个sql语句好像查不了所有类型为1的用户号,原谅我数据库学的太烂

     select  a.*  from   (select table.yhh from table  where table.lx=1) a  union  select b.*,c.* from (select table.yhh from table  where  table.lx=2) b ,(select table.yhh from table  where table.lx=3) c where a.yhh=b.yhh or (a.hh=b.yhh and a.yhh=c.yhh);

不知道后面where条件能不能访问到a表如果不能就改为

    select  a.*  from   (select table.yhh from table  where table.lx=1) a  union  select b.*,c.* from (select table.yhh from table  where table.lx=1) a ,(select table.yhh from table  where  table.lx=2) b ,(select table.yhh from table  where table.lx=3) c where a.yhh=b.yhh or (a.hh=b.yhh and a.yhh=c.yhh);

思路我是这么理解的:
当用户号只有类型=1时, 表中的这个用户记录数(即count)为1;
当用户号的类型为(1, 2)时,表中该用户记录数count为2;
同样地,当用户号的类型为(1,2,3)时,表中该用户的记录数count为3.
那么,可以通过这三个条件按照用户号分组后,做或操作。或者也可以理解为union操作,查询出符合这些条件的用户。

假设你的表名为userInfo, 用户号字段名为userNo, 类型字段名为userType. 通过这三个条件按照用户号分组后,做或操作,mysql语句可以这么写:
select userNo, count(userNo) as userCount , userType
from userInfo
group by userNo
having (userType=1 and count(userNo) =1)
or (u.userType in (1, 2) and count(userNo)=2)
or (userType in(1,2,3) and count(userNo)=3) ;

其实这个思路和一楼楼主danielinbiti 的思路是一致的。
只不过danielinbiti用了链接来实现count(userNo) 计数,
我是用了group by 语句直接在一个表里查询得到count(userNo) 。

或者你也可以将having 语句中的or条件拆分出来,用union来替代:

(select userNo, count(userNo) as userCount , userType
from userInfo
group by userNo
having (userType=1 and count(userNo) =1) )
union
(select userNo, count(userNo) as userCount , userType
from userInfo
group by userNo
having (u.userType in (1, 2) and count(userNo)=2) )
union
(select userNo, count(userNo) as userCount , userType
from userInfo
group by userNo
having (userType in(1,2,3) and count(userNo)=3) ) ;

P.S.:写mysql语句过程中顺便发现了个csdn的Bug--就是在评论的文本框内编辑,遇到字符*字体就会自动变成斜的格式, 需要用反斜杠\来转义*字符,也就是*才能正常识别。^_^

select distinct userNo from userInfo
where userNo not in (
select u.userNo from userInfo u
inner join (select userNo, count(userNo) as userCount from userInfo group by userNo) t
on u.userNo=t.userNo
where u.userType>t.userCount);