我必须找到一个用户出现在两个不同表中的次数...现在我使用了一个联合
我有此查询并且我想要记录<{1}}我的记录
SUM
我的结果:
(SELECT s.proprietario_id as p, COUNT(*) as conta
FROM sn_like_spotted s
GROUP BY s.proprietario_id
ORDER BY COUNT(*) DESC, s.id ASC
)
UNION ALL
(SELECT s.proprietario_id as p, COUNT(*) as conta2
FROM sn_like_risposta s
GROUP BY s.proprietario_id
ORDER BY COUNT(*) DESC, s.id ASC
)
我希望p具有最大总和
结果应为
p conta
1 33
2 15
3 1
4 11
5 2
1 20
2 9
4 2
9 2
18 5
19 7
答案 0 :(得分:2)
使用子查询!
SELECT p, SUM(conta) AS conta
FROM (
SELECT s.proprietario_id as p, COUNT(*) as conta
FROM sn_like_spotted s
GROUP BY s.proprietario_id
UNION ALL
SELECT s.proprietario_id as p, COUNT(*) as conta2
FROM sn_like_risposta s
GROUP BY s.proprietario_id
) AS baseview
GROUP BY p
ORDER BY conta DESC, p ASC
修改强>
我保留/粘贴您的原始查询,这会产生错误的排序 - 现在已修复。
答案 1 :(得分:0)
我不知道mySQL,但是你不想将结果集合在一起,然后再进行分组吗?
概念上类似于
SELECT s.proprietario_id as p, COUNT(*) as conta
from
((SELECT s.proprietario_id as p
FROM sn_like_spotted s
)
UNION ALL
(SELECT s.proprietario_id as p
FROM sn_like_risposta s
))
GROUP BY s.proprietario_id
ORDER BY COUNT(*) DESC, s.id ASC
答案 2 :(得分:0)
如果您希望p
使用最大总和:
select p, sum(conta) as conta
from ((SELECT s.proprietario_id as p, COUNT(*) as conta
FROM sn_like_spotted s
GROUP BY s.proprietario_id
)
UNION ALL
(SELECT s.proprietario_id as p, COUNT(*) as conta
FROM sn_like_risposta s
GROUP BY s.proprietario_id
)
) u
GROUP BY p
ORDER BY sum(conta) DESC, s.id ASC
LIMIT 1;
limit 1
为您带来最高价值。请注意,子查询中的order by
是不必要的,您只需要外部查询中的顺序。
此外,在union
中,列以第一个select
中的名称命名。别名conta2
有点不合适,因为该列名为conta
。
顺便说一句,您也可以在子查询中编写没有聚合的查询:
select p, sum(conta) as conta
from ((SELECT s.proprietario_id as p, 1 as conta
FROM sn_like_spotted s
)
UNION ALL
(SELECT s.proprietario_id as p, 1 as conta
FROM sn_like_risposta s
)
) u
GROUP BY p
ORDER BY sum(conta) DESC, s.id ASC
LIMIT 1;
在某些情况下,这可能会有更好的表现。