0

tweetsテーブル内の各ユーザーのすべてとretweets(すべてのリツイートもツイートです)をカウントする必要があります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 に答える