2017-04-24 99 views
-1
Game(p1, p2, pointsp1, pointsp2,), 
Participant(name, club, age) 

FK Game(p1) references Participant(name), 
FK Game(p2) references participant(name) 

這是我的關係模式,我試圖返回與會者誰參加了比賽,但沒有贏得的名稱的列表...如何在SQL中使用NOT IN?

所以,我有

  1. 收集了所有名,
  2. 刪除從誰的名字都通過贏得不存在
  3. 刪除了所有的抽獎名

但是我無法消除那些沒有參加比賽的人,但仍然以參賽桌的名字列。

我的代碼這部分工作不

{ 
SELECT name 
FROM Participant 
JOIN Game 
WHERE Participant.name!=Game.p1 
    OR Participant.name!=Game.p2 
} 

這是我的完整代碼:

SELECT name 
FROM Participant P 
WHERE name NOT IN (
    SELECT DISTINCT p1 
    FROM Game G 
    WHERE pointsp1 > pointsp2 
    UNION ALL 
    SELECT DISTINCT p2 
    FROM Game G 
    WHERE pointsp1 < pointsp2 
    UNION ALL 
    SELECT ender 
    FROM Game G 
    WHERE pointsp1 = pointsp2 
    UNION ALL 
    SELECT starter 
    FROM Game G 
    WHERE pointsp1 = pointsp2 
    UNION 
    SELECT name 
    FROM Participant 
    JOIN Game 
    WHERE Participant.name!=Game.p1 
     OR Participant.name!=Game.p2 
) 
+0

的可能的複製[未在SQL語句中?(http://stackoverflow.com/questions/10132371/not-in-in-sql-statement) –

回答

0

假設你只是想誰曾經玩過一個遊戲參與者的名單,但沒有獲得, 嘗試這個。

select name 
from participant 
where name not in (
    select case 
     when g.pointsp1 < g.pointsp2 then p2 
     when g.pointsp1 > g.pointsp2 then p1 
     end as winner 
    from game g 
    where g.pointsp1 != g.pointsp2 
) 
    and name in (
    select p1 from game 
    union all 
    select p2 from game 
) 

第一子選擇獲取所有獲獎者(和忽略的關係),第二個得到所有參與者在所有的遊戲。這不是一個很好的完成任務的方法,但它會起作用。

+0

謝謝MJ它的工作! –

0

你可以像下面的東西。

SELECT name 
FROM Participant P 
WHERE name NOT IN (
    SELECT DISTINCT p1 
    FROM Game G 
    WHERE pointsp1 > pointsp2 
    UNION ALL 
    SELECT DISTINCT p2 
    FROM Game G 
    WHERE pointsp1 < pointsp2 
    UNION ALL 
    SELECT ender 
    FROM Game G 
    WHERE pointsp1 = pointsp2 
    UNION ALL 
    SELECT starter 
    FROM Game G 
    WHERE pointsp1 = pointsp2) 
OR name not in (
    select p1 from game 
    union all 
    select p2 from game 
) 
相關問題