我在stackoverflow上找到了很多有用的信息,但是仍然缺少一点点来解决以下问题:
我有两个表usercores和userpoints像这样:
#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
我能够找出如何使用以下方法计算当前月份的最近用户点和存储的用户点(来自表“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 中存在但表 usercores 中不存在的用户 ID。
应该修改查询,以便新创建的用户 ID(在表 userpoints 中)也被视为分数。
我发现了如何查询以获取表 usercores 中不存在的用户 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;
任何帮助表示赞赏。