INTERSECT MySql

时间:2015-05-20 08:50:23

标签: mysql sql

我试图获得几个SQL请求的交集。我尝试了很多命令,但我仍然坚持。

以下是3个请求。

任何人都有想法帮助我吗?

1

SELECT username
FROM mdl_user
INNER JOIN mdl_quiz_grades
ON mdl_user.id=mdl_quiz_grades.userid
WHERE mdl_quiz_grades.quiz = 17;

2

SELECT username
FROM mdl_user
INNER JOIN mdl_quiz_grades
ON mdl_user.id=mdl_quiz_grades.userid
WHERE mdl_quiz_grades.quiz = 16;

3

SELECT username
FROM mdl_user
INNER JOIN mdl_quiz_grades
ON mdl_user.id=mdl_quiz_grades.userid
WHERE mdl_quiz_grades.quiz = 15;

1 个答案:

答案 0 :(得分:0)

使用联接可以轻松地重写INTERSECT:

SELECT t1.username
from 
 (
   SELECT username
   FROM mdl_user
   INNER JOIN mdl_quiz_grades
   ON mdl_user.id=mdl_quiz_grades.userid
   WHERE mdl_quiz_grades.quiz = 17
 ) as t1
join
 (
   SELECT username
   FROM mdl_user
   INNER JOIN mdl_quiz_grades
   ON mdl_user.id=mdl_quiz_grades.userid
   WHERE mdl_quiz_grades.quiz = 16
 ) as t
on t1.username = t2.username
join
 (
   SELECT username
   FROM mdl_user
   INNER JOIN mdl_quiz_grades
   ON mdl_user.id=mdl_quiz_grades.userid
   WHERE mdl_quiz_grades.quiz = 15
 ) as t3
on t1.username = t3.username

但在你的情况下,它几乎是相同的查询,只是不同的WHERE条件。您可以应用聚合逻辑:

SELECT username
FROM mdl_user
INNER JOIN mdl_quiz_grades
ON mdl_user.id=mdl_quiz_grades.userid
WHERE mdl_quiz_grades.quiz in (15,16,17)
GROUP BY username
HAVING COUNT(*) = 3

如果相同的用户ID可能多次具有相同的测验,则需要应用DISTINCT:

HAVING COUNT(DISTINCT quiz) = 3