2010-04-27 243 views
4

我試圖做一個查詢,查看一張表,看看一個學生是否在一個叫做CMHT的團隊和醫療隊 - 如果他們是我不想看到結果。查詢幫助

我只希望看到記錄,如果他們只在CMHT或軍醫,而不是兩個。

正確的方向是使用子查詢過濾出來嗎?我已經搜索了不在,但你怎麼能看看它是否在2個以上的球隊不是?

Student  Team   ref 
1   CMHT   1 
1   Medic   2 
2   Medic   3 this would be in the result 
3   CMHT   5 this would be in the result 

到目前爲止,我已經做了下面的代碼,我需要使用子查詢或做一個自我加入和過濾它的方式嗎?

SELECT Table1.Student, Table1.Team, Table1.refnumber 
    FROM Table1 
WHERE (((Table1.Team) In ('Medics','CMHT')) 

+0

還有其他r團隊?如果他們既不在'Medic'也不在'CMHT'中,您是否想要返回學生? – Quassnoi 2010-04-27 17:19:00

回答

2

這是馬克·拜爾斯的用HAVING子句而不是子查詢回答:

SELECT Student, Team, ref 
FROM Table1 
GROUP BY Student 
HAVING COUNT(Student) = 1 
+0

嘿 謝謝:) dint認爲做一個計數.. :) – user319160 2010-04-27 18:22:38

+0

o ps謝謝大家的幫助:) - 在另一個主題上如何外連接工作? – user319160 2010-04-27 18:23:15

+0

@ hdoe123:另一個主題=另一個問題。 – 2010-04-27 18:39:12

1
SELECT * 
FROM students 
WHERE NOT EXISTS 
     (
     SELECT NULL 
     FROM students si 
     WHERE si.student = s.student 
       AND si.team = 'CMHT' 
     ) 
     OR NOT EXISTS 
     (
     SELECT NULL 
     FROM students si 
     WHERE si.student = s.student 
       AND si.team = 'Medic' 
     ) 
1
SELECT a.* 
FROM Table1 a 
INNER JOIN 
(SELECT Student, COUNT(*) FROM Table1 
GROUP BY Student 
HAVING COUNT(*) = 1)b 
ON (a.Student = b.Student) 
1

如何,你可以在這裏看到檢查其在2個人以上的團隊?

你可以指望每個學生團隊的數量,然後篩選只有那些你希望看到:

SELECT student FROM 
(
    SELECT student, COUNT(*) AS cnt 
    FROM Table1 
    GROUP BY student 
) T1 
WHERE cnt = 1 
1

你可以用外做加盟

select COALESCE(t1.Student, t2.Student) as Student, 
     COALESCE(t1.Team, t2.Team) as Team, 
     COALESCE(t1.ref, t2.ref) as ref 
from 
    (select * from Student where Team = 'CMHT') t1 
    outer join 
    (select * from Student where Team = 'Medic') t2 
    on t1.Student = t2.Student 
where 
    t1.Student is null or 
    t2.Student is null; 
+0

'MySQL'不支持'FULL OUTER JOIN'。 – Quassnoi 2010-04-27 17:41:25

+0

對不起,不知道。看到這個問題也被標記爲tsql,並認爲SqlServer語法和外連接行爲是有效的。 – Fede 2010-04-27 18:51:44