mysql中and 和 or 联合使用

以下是两张表,我只列出有用的字段。
Table:student_score 学生成绩
sid(学生ID) cid(课程ID) score(分数)
5 1 50
5 2 110
5 3 64
5 4 null
……
Table:course 课程
id(ID) name(课程名) inexam(是否考了)
1 语文 1
2 数学 1
3 英语 1
4 理综 0

现在我要取出某次考试中语文成绩中高于80或低于40的学生ID,PHP中SQL语句可以这么写:

$sql="select s.sid from student_score as s,course as c where (s.score>=80 or s.score<=40) and s.cid=1 and s.cid=c.id and   c.inexam=1";

这里用一个小括号把两个用or组合起来的条件括了起来。

如果我要取出某次考试中语言成绩高于80数学成绩高于100的学生呢?这么写:

$sql="select s.sid from student_score as s,course as c where ((s.score>=80 and s.cid=1) or (s.score>=100 and s.cid=2) )   and s.cid=c.id and c.inexam=1";

总结:当mysql的WHERE语句中出现AND OR时,使用OR组合的并列条件要用小括号把两个条件和”OR”包起来。

文章转自:

https://blog.csdn.net/rongwenbin/article/details/27494069

原文地址:https://www.cnblogs.com/zhaopengcheng/p/9453013.html