2016-05-25 2 views
1

これは些細なことでよろしいですか?私はPostGRESQLを初めて使用しています。私は今、質問に回答する必要がありPostgreSQLで効率的なクエリを作成してステートメントを統合する

CREATE TABLE group_users (
    user_id int NOT NULL PRIMARY KEY, 
    group_id int NOT NULL, 
    join_time timestamp NOT NULL, 
    member_rank enum('l','a','m') DEFAULT NULL 
); 

CREATE TABLE interactions (
    interactionid int PRIMARY KEY NOT NULL, 
    user_id int NOT NULL, 
    target_user_id int NOT NULL, 
    start_time timestamp NOT NULL 
); 

::私は2つの のテーブルを与えられています

との間の相互作用の割合は何か:任意のグループ内の別のグループ内のユーザ、グループ内 ユーザー対それらではないが、 、同じユーザーのグループのユーザー グループ?

これは私のクエリですが、1つのクエリにまとめなければなりません。 PostgreSQLでこれを行うには、より効率的な方法があり、以下のクエリについて

  1. :ある

    私の質問?

  2. この1つのクエリを作成する最も効率的な方法は何でしょうか?

- 相互作用情報

CREATE TEMPORARY TABLE group_interaction_information AS 
SELECT 
a.interactionid, 
a.user_id, 
b.group_id, 
a.target_user_id, 
c.group_id AS target_group_id 
FROM interactions a 
LEFT JOIN 
group_users b 
on a.user_id = b.user_id 
LEFT JOIN 
group_users c 
ON a.target_user_id = c.user_id; 

とgroup_idsにマップuser_ids - 差のグループ内のユーザの相互作用の割合

select 
(select count(*) from group_interaction_information 
where group_id != target_group_id and group_id is not null 
and target_group_id is not null)/(select count(*) from group_interaction_information)::float; 

- グループ内のユーザからの相互作用の割合

select 
(select count(*) from group_interaction_information 
where group_id is not null)/ 
(select count(*) from group_interaction_information)::float; 

- ユーザーからのいないグループの相互作用の割合

select 
(select count(*) from group_interaction_information where group_id is null)/ 
(select count(*) from group_interaction_information)::float; 

- 同じグループ内のユーザからの相互作用の割合クエリを結合する

select 
(select count(*) from group_interaction_information 
where group_id = target_group_id and group_id is not null 
and target_group_id is not null)/(select count(*) from group_interaction_information)::float; 

答えて

1

一つの方法は、条件付きの集約である。

ところで、a = bは、どちらか一方または両方の列がnullの場合は決して真ではないので、group_id = target_group_idand target_group_id is not nullを指定する必要はありません。同じことがa <> bにも当てはまります。実行select null = null, null <> null, 'a' <> nullをテストするには、すべてnullになります。

+0

これは素晴らしいです!どうもありがとうございます!私は多くを学ぶ:) – RDizzl3

+0

@ RDizzl3うれしい私は助けることができる:) – FuzzyTree

関連する問題