2012-06-18 26 views
0

我发现了很多关于计算器有用的信息,但一点点仍然缺少解决了以下问题:使用MySQL计算两个表之间的每月用户内核?

我有两个表userscoresuserpoints这样的:

#table userscores (saves userpoints each month) 

date   userid points 
2012-05-01 1  23 
2012-06-01 1  34 


#table userpoints (recent points) 

userid points 
1  23 
2  10 
3  15 

我能找出如何计算recen之间的差异采用t userpoints和存储userpoints(来自表“userscores”)当前月的:

SELECT userpoints.userid, userpoints.points - userscores.points AS mpoints 
    FROM `userpoints`,`userscores` 
    WHERE userpoints.userid=userscores.userid 
     AND YEAR(userscores.date) = YEAR(CURDATE()) 
     AND MONTH(userscores.date) = MONTH(CURDATE()) 
     AND userpoints.userid != ".$adminID." 
    ORDER BY mpoints DESC;" 

然而,该查询仅来自两个表进行比较的用户ID和忽视存在于表userpoints的用户ID和但不存在于表用户核心中。

应该修改查询,以便新创建的用户标识(在表用户标记中)也被视为分数。


我发现了如何查询以获得不表userscores存在用户ID:

SELECT userpoints.userid FROM `userpoints` 
     WHERE userpoints.userid 
      NOT IN(SELECT qa_userscores.userid FROM `qa_userscores`) 


现在我必须结合了但尝试以下不工作:

SELECT userpoints.userid, userpoints.points - userscores.points AS mpoints 
FROM `userpoints`,`userscores` 
WHERE ( 
    userpoints.userid = userscores.userid 
    AND YEAR(userscores.date) = YEAR(CURDATE()) 
    AND MONTH(userscores.date) = MONTH(CURDATE()) 
    AND userpoints.userid != ".$adminID." 
) 
OR ( 
    userpoints.userid IN(SELECT userpoints.userid FROM `userpoints` 
     WHERE userpoints.userid 
      NOT IN(SELECT DISTINCT userscores.userid FROM `userscores`)) 
) 
ORDER BY mpoints DESC; 


任何帮助表示赞赏。

回答

1
SELECT userpoints.userid, userpoints.points - coalesce(userscores.points,0) 
               AS mpoints 
    FROM `userpoints` 
    left join `userscores` on userpoints.userid=userscores.userid   
     AND YEAR(userscores.date) = YEAR(CURDATE()) 
     AND MONTH(userscores.date) = MONTH(CURDATE()) 
    where userpoints.userid != ".$adminID." 
    ORDER BY mpoints DESC;" 

左连接即使在右侧没有对应的行时也会自动保留左侧的行。您在右侧检查的所有条件必须处于“加入条件”中。最后,当ther没有时,您需要为右侧值使用默认值。

+0

完美,非常感谢srini.venigalla!我将在我目前为www.question2answer.org –

+0

写的插件中赞扬你哦!我很荣幸,先生! –

0

您可以使用UNION组合来自两个查询的结果。

SELECT userpoints.userid, userpoints.points - userscores.points AS mpoints 
    FROM `userpoints`,`userscores` 
    WHERE userpoints.userid=userscores.userid 
     AND YEAR(userscores.date) = YEAR(CURDATE()) 
     AND MONTH(userscores.date) = MONTH(CURDATE()) 
UNION 

SELECT userpoints.userid, points as mpoints FROM `userpoints` 
     WHERE userpoints.userid 
      NOT IN(SELECT userscores.userid FROM `userscores`) 

上的UNION使用更多的信息,请参阅mysql documentation

相关问题