2015-05-20 45 views
1

我想獲得幾個SQL請求的交集。我嘗試了很多命令,但仍然卡住了。INTERSECT MySql

以下是3個請求。

任何人都有想法來幫助我?

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

考慮提供一些示例數據和預期的結果。 –

回答

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可能有你需要的應用獨特的同一測驗多次:

HAVING COUNT(DISTINCT quiz) = 3 
+0

非常感謝,完美的作品! –