我对联接查询有疑问。 我有3张桌子:
机器
+-----+--------+
| mid | points |
+-----+--------+
| 12 | 25 |
| 22 | 50 |
| 23 | 75 |
| 30 | 90 |
+-----+--------+
挑战
+----+-----+-----+
| id | mid | uid |
+----+-----+-----+
| 1 | 22 | 9 |
| 2 | 23 | 10 |
| 3 | 29 | 13 |
| 4 | 12 | 10 |
+----+-----+-----+
user_hints
+----+-----+-----+
| id | mid | uid |
+----+-----+-----+
| 1 | 22 | 10 |
| 2 | 23 | 10 |
| 3 | 30 | 10 |
| 4 | 22 | 11 |
+----+-----+-----+
我正在尝试创建一个查询,该查询会将特定用户的一些统计信息收集到一行中。
预期结果是:
+--------+------------+
| points | totalhints |
+--------+------------+
| 100 | 3 |
+--------+------------+
这是我的查询
SELECT challenges.id,
IFNULL(
( SELECT SUM(m.points) as points
FROM challenges c
INNER JOIN machines m ON (c.mid = m.mid AND c.uid = 10)
GROUP BY c.uid),'0') AS points,
COUNT(*) as totalhints
FROM challenges
RIGHT OUTER JOIN user_hints uh ON user_hints.uid = 10
GROUP BY points
,但是总提示关闭并且正在计数所有行。 在最后的INNER JOIN部分可以得到一些帮助吗? 谢谢
答案 0 :(得分:1)
您可以执行以下操作,但实际上,当您将各种不同的内容混在一起时,我认为最好在单独的查询中执行此操作...
SELECT DISTINCT j.uid
, COALESCE(k.points,0) points
, COALESCE(l.hints,0) hints
FROM challenges j
LEFT
JOIN (SELECT c.uid, SUM(points) points FROM challenges c JOIN machines m ON m.mid = c.mid GROUP BY c.uid) k
ON k.uid = j.uid
LEFT
JOIN (SELECT uid, COUNT(h.id) hints FROM user_hints h GROUP BY uid) l
ON l.uid = j.uid;