左连接子查询NOT IN

时间:2013-10-09 16:08:44

标签: mysql sql

team_members,usertable和pointstable

首先需要让所有用户不在team_members表中

我用

做了这个
SELECT UserID
FROM usertable
WHERE UserID NOT 
IN (SELECT UserID FROM team_members)
AND Location =  'my loctaion'

这很好用

但现在我需要根据usertable

中的UserID从points表中获取一些信息
SELECT usertable.* , pointstable.UserID, SUM( pointstable.RemainderPoints ) 
AS points FROM   usertable LEFT JOIN pointstable ON usertable.UserID = pointstable.UserID
WHERE  usertable.UserID NOT IN (SELECT usertable.UserID FROM team_members)
GROUP BY usertable.UserID 

这不会返回任何内容

任何想法?

3 个答案:

答案 0 :(得分:1)

请注意,您的原始查询可以按如下方式重写:

SELECT UserID
  FROM usertable u
  LEFT
  JOIN team_members tm
    ON tm.userid = u.userid
 WHERE Location =  'my location'
   AND tm.userid IS NULL;

答案 1 :(得分:0)

尝试以下方法:

select users.UserID,Pointstable.UserID,SUM(remainderpoints) from Users
left join  Pointstable
 on users.UserID=Pointstable.UserID
where users.userid not in (SELECT usertable.UserID FROM team_members)
  group by users.UserID, pointstable.UserID

如果您需要在选择部分中的用户表中添加更多列,请将其添加到组中。

答案 2 :(得分:0)

接受了你的所作所为......以防万一其他人对此有任何问题

 SELECT usertable.*,pointstable.UserID, SUM( pointstable.RemainderPoints ) AS points ,team_members.* 
FROM usertable LEFT JOIN pointstable ON usertable.UserID = pointstable.UserID
LEFT JOIN team_members ON pointstable.UserID = team_members.UserID 
WHERE usertable.Location =  'South Molton'
AND team_members.UserID IS NULL GROUP BY usertable.UserID