我一直在为这段代码苦苦挣扎。我复制了它,并从另一个SO问题中改变了它,但是我无法让它工作。
我有一个表(分数),其中包含用户名,用户ID和分数。和另一个名为userLocations的表,它包含userID,city,country,lat和long坐标。
我需要做的是列出得分表中的每一行,表中userLocation中的行没有相同的用户ID。
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 :(得分: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_exists
为0
的行,请在查询中添加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;
答案 1 :(得分:1)
如果您只想获得scores
中userid
中不匹配userLocations
select * from scores s
where not exists (
select 1 from userLocations ul
where ul.userID = s.userID
)
的行列表,我相信此查询应该会为您提供良好的效果:
{{1}}