1

我正在尝试根据他们提交到 2 个不同表的条目数对我的用户进行排名。

表 gvr:

rid | jid 
---------------
1     54
2     54
3     54
4     75
5     75

表去:

sid | jid
---------------
1     54
2     54
3     75
4     75
5     23
6     23

期望的结果:

jid | overall_cnt | gvr_cnt | gos_cnt
----------------------------------
54    5            3          2
75    4            2          2
23    2            0          2

我有:

(SELECT jid, count(*) gvr_count
FROM gvr 
WHERE jid IS NOT NULL
GROUP BY jid)
UNION ALL 
(SELECT jid, count(*) gos_count
FROM gos
WHERE jid IS NOT NULL
GROUP BY jid)

但这是非常不正确的。我一直在寻找与我的情况类似的其他帖子,但还没有找到任何有价值的东西。我正在考虑将数据操作加载到 PHP 上,但在一个查询中完成它会很方便。

4

4 回答 4

2

您的查询非常接近。你想要union all然后做一个group by

select jid, sum(gvr_count) + sum(gos_count) as Overall_Count,
        sum(gvr_count) as gvr_count, sum(gos_count) as gos_count
from ((SELECT jid, count(*) gvr_count, 0 as gos_count
       FROM gvr 
       WHERE jid IS NOT NULL
       GROUP BY jid
      )
      UNION ALL 
      (SELECT jid, 0 as gvr_count, count(*) gos_count
       FROM gos
       WHERE jid IS NOT NULL
       GROUP BY jid
      )
     ) t
group by jid

我认为这是 MySQL 中确保您获得所有“jid”的最佳方法,即使是那些仅在一个表中的。

于 2013-03-02T21:52:09.667 回答
2

我更新了 Gordon 的答案,这是最好的方法。

 select jid ,sum(gvr_count)+ sum(gos_count) as OverallCount ,
  sum(gvr_count) as gvr_count, sum(gos_count) as gos_count
   from ((SELECT jid, count(*) gvr_count, 0 as gos_count
   FROM gvr 
   WHERE jid IS NOT NULL
   GROUP BY jid
  )
  UNION ALL 
  (SELECT jid, 0 as gvr_count, count(*) gos_count
   FROM gos
   WHERE jid IS NOT NULL
   GROUP BY jid
  )
 ) t
group by jid
于 2013-03-02T22:01:17.950 回答
1
SELECT temp.jid,gvr_cnt + gos_cnt as totals,temp.*
FROM
(
SELECT gos1.jid
,(SELECT COUNT(*) from gvr where gvr.jid = gvr1.jid) AS gvr_cnt
,(SELECT COUNT(*) from gos where gos.jid = gos1.jid) AS gos_cnt
FROM gos gos1 left join gvr gvr1 on gos1.jid = gvr1.jid
group by gos1.jid
  ) as temp
group by temp.jid

SQL 小提琴演示

于 2013-03-02T21:47:21.317 回答
0

这可能不完全正确,但我希望你能从这里得到它:

SELECT innerQuery_1.jid AS jid, 
       (innerQuery_1.gvr_count + innerQuery_2.gos_count) AS overall_cnt, 
       innerQuery_1.gvr_count AS gvr_count,
       innerQuery_2.gos_count AS gos_count
FROM   (SELECT jid, count(*) gvr_count
        FROM   gvr 
        WHERE  jid IS NOT NULL
        GROUP BY jid) AS innerQuery_1,
       (SELECT jid, count(*) gos_count
        FROM   gos
        WHERE jid IS NOT NULL
        GROUP BY jid) AS innerQuery_2
GROUP BY innerQuery_1.jid
于 2013-03-02T21:46:00.583 回答