2014-11-01 51 views
0

我一直在爲這段代碼苦苦掙扎了一段時間。我複製了它,並從另一個SO問題中修改了它,但我無法實現它。mysql:從table1中的表中選擇缺少的行0

我有一個表(分數),其中包含用戶名,用戶名和分數。和另一個名爲userLocations的表,其中包含userID,城市,國家,經緯度和長度座標。

我需要做的是列出scores-table中的每一行,這個行在表userLocation中沒有一個具有相同userID的行。

select scores.userID , case when userLocations.userID is not null then 1 else 0 end as row_exists from scores left outer join (select distinct userID from userLocations) userLocations on scores.userID = userLocations.userID 
+0

選擇x * FROM分數X LEFT JOIN用戶位置是開y.userid = x.user WHERE y.userid IS NULL – Strawberry 2014-11-01 16:04:08

回答

1

如果你想要的是讓在scores行的列表沒有在userLocations匹配userid我相信這查詢應該給你,有良好的表現。

select * from scores s 
where not exists (
    select 1 from userLocations ul 
    where ul.userID = s.userID 
    ) 
+0

感謝,這是一個非常明確的答案。 – Runar 2014-11-02 09:48:34

2

這是您的查詢:

select scores.userID , case when userLocations.userID is not null then 1 else 0 end as row_exists 
from scores left outer join 
    (select distinct userID from userLocations) userLocations 
    on scores.userID = userLocations.userID; 

你需要一個left join。我也主張表的別名使查詢更容易編寫和閱讀:

select s.userID , (case when ul.userID is not null then 1 else 0 end) as row_exists 
from scores s left outer join 
    (select distinct userID from userLocations) ul 
    on s.userID = ul.userID; 

如果你只想要行,其中row_exists0,再加入where ul.userId is NULL到查詢。事實上,在這種情況下,編寫查詢的最好的辦法是不子查詢:

select s.userID , (case when ul.userID is not null then 1 else 0 end) as row_exists 
from scores s left outer join 
    userLocations ul 
    on s.userID = ul.userID 
where ul.userId is NULL;