简体   繁体   English

SQL 选择其中 A 等于 B 和 C

[英]SQL selecting where A equals both B and C

name | course
Jay | LAWS0001
Mark | LAWS0002
Sam | LAWS0002
Alice | LAWS0001
Ryan | LAWS0001
Ryan | LAWS0002

Hey guys, I've got this database and I want to only select the names that take both 'LAWS0001' and 'LAWS0002'.嘿伙计们,我有这个数据库,我只想选择同时包含“LAWS0001”和“LAWS0002”的名称。 So from this example, it should select 'Ryan' because he's the only person to take both courses.所以从这个例子中,它应该选择“Ryan”,因为他是唯一参加这两个课程的人。 I tried IN operator:我试过 IN 运算符:

SELECT name
FROM student
WHERE course IN ('LAWS0001', 'LAWS0002')

but this takes everyone because everyone is taking either of the courses.但这需要每个人,因为每个人都在学习任何一门课程。

Is there an operator for my problem?我的问题有接线员吗?

You can use your existing query, using a GROUP BY clause to COUNT the number of distinct courses each student is taking in the set ('LAWS0001', 'LAWS0002') and only selecting those students where the count is 2:您可以使用现有的查询,使用GROUP BY子句COUNT的不同课程,每个学生走在集数('LAWS0001', 'LAWS0002')只有选择那些学生,其中数为2:

SELECT name
FROM student
WHERE course IN ('LAWS0001', 'LAWS0002')
GROUP BY name
HAVING COUNT(DISTINCT course) = 2

Demo on SQLFiddle SQLFiddle 上的演示

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

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