我在stackoverflow上找到了很多有用的信息,但是仍然缺少一点来解决以下问题:
我有两个表用户数和用户点:
#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和忽略表用户点中存在但用户表中不存在的用户ID 。
应修改查询,以便新创建的用户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;
任何帮助表示赞赏。
答案 0 :(得分: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;"
即使右侧没有相应的行,左连接也会自动保留左侧的行。您在右侧检查的所有条件必须在加入条件中。最后,如果没有,则需要使用右侧值的默认值。
答案 1 :(得分: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。