对COUNT(*)使用RIGHT OUTER JOIN

时间:2018-10-28 15:25:22

标签: mysql

我对联接查询有疑问。 我有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 |
+----+-----+-----+

我正在尝试创建一个查询,该查询会将特定用户的一些统计信息收集到一行中。

  1. 对于CHALLENGES表中具有相应用户ID(“ uid”列)的所有记录-从MACHINES表“ points”列中计算总点数。它们与“ mid”列相关。如果没有记录/点,则返回0。
  2. 对于相同的用户ID(uid列)-计算USER_HINTS表中的记录数,并将其加入到第一次查询的结果中。

预期结果是:

+--------+------------+
| 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部分可以得到一些帮助吗? 谢谢

1 个答案:

答案 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;