Search code examples
phpmysqlsqlranking

Counting the number of overall entries from 2 different tables


I am trying to rank my users by the number of entries they have submitted to 2 different tables.

table gvr:

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

table gos:

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

Desired results:

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

I have:

(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)

But this is grossly incorrect. I have been searching for through other posts similar to my situation but could not find anything of too much value yet. I am thinking of off loading the data manipulation onto PHP, but it would be convenient to do it in one query.


Solution

  • I updated Gordon answer this is the best approach.

     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