2013-03-02 99 views
1

我想根據他們提交給2個不同表的條目數來對用戶進行排名。計算來自2個不同表格的總體條目數

表GVR:

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

表GOS:

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,但在一個查詢中執行它會很方便。

回答

2

我更新了戈登回答這是最好的方法。

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 
+0

這樣做的竅門! – Ramuk 2013-03-02 23:05:15

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 
+0

它沒有返回JID 23 – 2013-03-02 21:47:47

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 Fiddle Demo

+0

整體計數不正確 – 2013-03-02 21:50:04

+0

@syedmohsin - 看到更新後的演示吧。 – MuhammadHani 2013-03-02 21:56:25

+1

+1對我來說很好 – 2013-03-02 21:59:53

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」 S,即使是那些只在一個表中。

+0

查詢後我錯過了你在筆記中提到的條件:) – 2013-03-02 21:55:43

相關問題