0

我需要计算所有tweetsretweets(所有转发也是推文)表中的每个用户authors。我的第一个想法很有效:

推文柜台

SELECT a.id, a.name, count(*)
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)

转推柜台

SELECT a.id, a.name, count(*)
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id AND retweet = TRUE
GROUP BY a.id, a.name
ORDER BY count(*)

...但现在我想把所有这些放在一起。我想知道是否有比这更好(更快)的方法:

合并

SELECT a.id, a.name, count(*), (
    SELECT count(*) 
    FROM tweets 
    WHERE fromuser_id = a.id AND retweet = TRUE
)
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)
4

2 回答 2

1
SELECT a.id, a.name, count(*),
       SUM(CASE WHEN retweet = TRUE THEN 1 ELSE 0 END) as retweets_count
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)
于 2013-03-24T20:06:45.770 回答
1

是的,有更好的方法。使用条件求和:

SELECT a.id, a.name, count(*),
       sum(case when retweet = true then 1 else 0 end) as retweets
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)
于 2013-03-24T20:07:43.597 回答