数据查询问题

course_id  user_id

------------------------

244           302

244           342

246           342

225           302

248           342

 

 

我要把course_id=246和244 都满足的user_id查询出来

 

请问如何查询?


问题补充:
是都要满足...

in当然不行啦...
问题补充:
select distinct user_id   
from table_name  
where course_id =246 or course_id =244

和用in有区别么...错...
问题补充:
select distinct user_id   
from table_name  
where course_id =246
and exists (select user_id   
from table_name  b where b.user_id=user_id and b.course_id =244  )


错...
问题补充:
我用的是oracle,查询下来上面的补充还是错,和in没区别...
问题补充:
select  user_id   
from temp4 a   
where a.course_id =244  
and  exists(  
  select  *   
  from temp4 b   
  where course_id =246  
    and b.user_id = a.user_id  
);  

正确,但是太不灵活...

我已经想到了...

select user_id from(select user_id,count(user_id) num from user_course uc where uc.course_id in (246,244) group by user_id) where num=2;

不知各位如何觉得?

问题补充:
select user_id from(select user_id,count(user_id) num from user_course uc where uc.course_id in (246,244) group by user_id) where num=2;

补充:这个解法有问题,如果course_id 有244,247那不还是错。
xieye (中级程序员) 2009-06-05 采纳为答案


动态的,根据in()里的记录条数,决定num的值...
问题补充:
还有其他解吗?没有更好的解,我就关闭问题了...

实在不行就用个性能差的,比较土的:
select distinct a.user_id

from table_name a

where a.course_id =246
and a.user_id in (select b.user_id

from table_name b where b.course_id =244 )

[code="sql"]
select user_id
from table_name
where course_id in (246,244)
[/code]

select distinct user_id

from table_name

where course_id =246 or course_id =244

不好意思,我想想,应该有办法的

forgetOneself 的回答也是错误的,和我一样

感觉是要加括号吧,用or的话
select distinct user_id

from table_name

where (course_id =246 or course_id =244)

没明白他的意思,能说具体点吗

select distinct user_id

from table_name

where course_id =246
and exists (select user_id

from table_name b where b.user_id=user_id and b.course_id =244 )

这是完整的ORACLE的

select distinct a.user_id

from table_name a

where a.course_id =246
and exists (select b.user_id

from table_name b where b.user_id=a.user_id and b.course_id =244 )

[code="sql"]
select user_id
from temp4 a
where a.course_id =244
and exists(
select *
from temp4 b
where course_id =246
and b.user_id = a.user_id
);

[/code]
我已在mysql5.0测试通过,估计oracle也可以,因为这是标准sql。
楼主试试看!

我估计这道题的解法不只一种,
至少还可以使用sql的交集语法。
然后,不用交集,不用exists,还可以用join我估计也可以。

我很少用exists,楼主给了我一个机会学习sql,感动ing。。。

我建表测试,上面的两种情况,都可以,结果就是:342

select user_id from(select user_id,count(user_id) num from user_course uc where uc.course_id in (246,244) group by user_id) where num=2;

好像可以,不过要求给两个字段加联合唯一索引,最好要加,
forgetOneself比我先回答了正确答案。

select user_id from(select user_id,count(user_id) num from user_course uc where uc.course_id in (246,244) group by user_id) where num=2;
 

这一种不对,只是你举例的数据正好碰对了,如果244 342
这一条记录有重复一次的话,结果会怎么样?
从你的SQL语法上不严谨

select user_id from(select user_id,count(user_id) num from user_course uc where uc.course_id in (246,244) group by user_id) where num=2;

补充:这个解法有问题,如果course_id 有244,247那不还是错。

请把分给forgetOneself,这是我的强烈要求,没补充了。