简体   繁体   English

在WHERE子句中使用AND和OR进行MySQL查询

[英]MySQL query with AND and OR in WHERE clause

I am creating a student records search query. 我正在创建一个学生记录搜索查询。 The school has three clubs (maths, english and science). 学校设有三个俱乐部(数学,英语和科学)。 What i want to do is to select student by the club they have joined in this order. 我想做的是按他们按此顺序加入的俱乐部选择学生。 Student who are in -- Maths Only -- Maths and English only -- Maths and Science Only -- English Only -- English and Science Only -- Science Only 就读的学生-仅数学-仅数学和英语-仅数学和科学-仅英语-仅英语和科学-仅科学

Student table (studentTB)

id | student_name | date_join
-----------------------------
 1 | Daniel Addo  | 2012-01-05
 2 |David Polles  | 2013-05-11
 3 | Grace Amorno | ---------
 4 | Zein Akill   | ---------

Club table (studentCLUB)

id | studentID | club
----------------------
1  | 1         | maths
2  | 1         | science
3  | 2         | science
4  | 2         | english
5  | 3         | science
6  | 4         | maths
7  | 4         | science
8  | 4         | english


SELECT *
    FROM studentTB
    INNER JOIN studentCLUB
    ON studentTB.id = studentCLUB.studentID
    WHERE (club = 'maths') OR (club = 'science') OR (day = 'english')
    GROUP BY studentTB.id

This is what i have so far and it is selecting student when they fall within one of the club. 这是我到目前为止所拥有的,并且当他们属于其中一个俱乐部时正在选择学生。 But when i change the OR to AND it gives me null. 但是,当我将OR更改为AND时,它为空。 I will be glad if anyone can help me. 如果有人可以帮助我,我将非常高兴。 Thank you 谢谢

So it you need to find students who belongs to all the given club you can do as below. 因此,您需要找到属于所有给定俱乐部的学生,如下所示。 It will check the students having all the given 3 clubs. 它将检查拥有所有给定3个俱乐部的学生。

SELECT *
FROM studentTB
INNER JOIN studentCLUB
ON studentTB.id = studentCLUB.studentID
WHERE
club in ('maths','science','english') 
GROUP BY studentTB.id
having count(*) = 3 
SELECT * FROM studentTB
WHERE EXISTS(SELECT * FROM studentCLUB
WHERE studentTB.id = studentCLUB.studentID)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM