我正在尝试按照他们提交给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上,但在一个查询中这样做会很方便。
答案 0 :(得分: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,甚至是那些只在一个表中的那些。
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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