如,没有选修‘B2’课程的学生 :select students.*
from students, grades
where students.sno=grades.sno
AND grades.cno <> ’B2’这样写是错误的!!为什么?
from students, grades
where students.sno=grades.sno
AND grades.cno <> ’B2’这样写是错误的!!为什么?
from students,grades
where students.sno=grades.sno AND grades.cno <> 'B2'按上面的写法,语法上是没有什么错误的啊..你也可以这样来写,试试:
SELECT * FROM STUDENTS T
WHREE NOT EXISTS(SELECT * FROM GRADES WHERE SNO=T.SNO AND CNO='B2')
from students left join grades
on students.sno=grades.sno
where grades.cno <> ’B2’
from students,grades
where students.sno=grades.sno AND grades.cno <> 'B2'
这样写的前提必须是 sno 是students 和 grades 主键, 并且students中有的sno在grades中也必须要有,否则就会返回错误数据
楼上的语句正确
我的意思是按照上面那样写会返回错误数据(不是语法有错误)!!
而要这么写:select * from students
where not exists (select * from grades
where grades.sno=students.sno AND cno='B2')
则可以保证数据的正确,我不知道为什么!!
或者说为什么上面写容易产生错误数据!!!!!还有一个问题:
现行的主流数据库默认都是inner join.比如这样写:
select students.*
from students, grades
where students.sno=grades.sno
AND grades.cno <> ’B2’
等效于
select students.*
from students inner join grades
where students.sno=grades.sno
AND grades.cno <> ’B2’
1 B2
1 A2
2 A2
.....用你写的查询只能剔除掉1 B2这条,而学生编号为1的学生仍然有1 A2这条数据,也就是说你并未剔除掉选择了B2课程的学生1明白??
not exists
left join
是干什么的,再分析你的语句,就明白了,不想多说什么