我现在有两张表,
t1: student_id, student_name
t2:course_id, student_id, course_name
t1和t2是一对多的关系,通过student_id进行关联。
现在想做这样的查询,根据课程筛选学生名字
如:
1)选择了‘English’的学生
2)未选择‘Chinese’的学生
3) 选择了‘English’并同时选择了‘Chinese’的学生
4) 选择了‘English’并没有选择了‘Chinese’的学生
类似这样的查询,条件可以组合。
请教一下有没有什么比较简便的方法可以实现各种组合查询
1)select t1.student_name from t1,t2 where t1.student_id = t2.student_id and t2.course_name = 'English'
2)select t1.student_name from t1,t2 where t1.student_id = t2.student_id and t2.course_name <> 'Chinese'
3)select t1.student_name from t1,t2 where t1.student_id = t2.student_id and t2.course_name = 'English' or t2.course_name = 'Chinese'
4)select t1.student_name from t1,t2 where t1.student_id = t2.student_id and t2.course_name = 'English' and t2.course_name <> 'Chinese'
不知道这个是不是你要的结果。
组合查询的时候不对,比如3)查出来是修了english或chinese的学生。我希望的是两门同时修的
那就把 or 改成 and 就是你要的结果了
@北京_update: 也不对的,因为t2表不可能有哪一条记录同时满足两个条件。是t2表里的两条记录分别满足一个条件。
@c00164959:
select * from t1,t2,t2 as t22 where t1.student_id = t2.student_id and t1.student_id = t22.student_id and t2.student_id = t22.student_id
and t2.course_name = 'English' and t22.course_name = 'Chinese'
@c00164959:
4)select * from t1,t2 where t1.student_id = t2.student_id and t2.course_name = 'English' AND t1.student_id not in ( select student_id from t2 where course_name = 'Chinese')
@北京_update: 这样的话,有几个条件就需要对t2加几次别名了,是吧
@c00164959: 对的,加别名是其中一种方法,使用 student_id in (select .....) 是另外一种方法。
1.select student_name from t1
where exists(select 'X' from t2 where course_name='English' and t2.student_id=t1.student_id )
2.select student_name from t1
where exists(select 'X' from t2 where course_name='Chinese' and t2.student_id=t1.student_id )
3.select student_name from t1
where exists(select 'X' from t2 where course_name='Chinese' and t2.student_id=t1.student_id )
and exists(select 'X' from t2 where course_name='English' and t2.student_id=t1.student_id )
4.select student_name from t1
where exists(select 'X' from t2 where course_name='Chinese' and t2.student_id=t1.student_id )
and not exists(select 'X' from t2 where course_name='English' and t2.student_id=t1.student_id )
postgre没有exists吧???
@c00164959: 失误,看错了,不过我找了一下,发现http://f.dataguru.cn/thread-454912-1-1.html有用到exists,我没试过,你可以看看。