行いたいこと
現在、4つのテーブルを参照してその中のカラムの合計値を出したいのですが、明らかに値が大きくなってしまいます。
調べたところ、inner joinを行うとテーブルのレコード数が重複してしまい、重複した値もsumに取り入れられてしまいます。
現状、inner joinの一つを from句の中に入れて1つのテーブルからの重複は免れたのですが、残り2つのテーブルが重複してしまいます。
回答わかる方いらっしゃいますでしょうか?
テーブルとカラム
-
usersテーブル
id name ... 1 test ... 2 aaaa ... 3 bbbb ... ... -
appsテーブル
id user_id name ... 1 2 app_test ... 2 2 cccc ... 3 2 dddd ... ... -
▲▲テーブル
id app_id ... 1 3 ... 2 1 ... 3 2 ... ... -
××テーブル
id app_id ... 1 2 ... 2 1 ... 3 3 ... ... -
出したい値
→ 同じuserが作成したappsの▲▲テーブルと××テーブルに紐づいた合計
ex:
aaaa(user_id:2)が作成したapp(ここでは、app_id:[1,2,3])に紐づく▲▲テーブルと××テーブルのカラム集計(sum)
試したこと
SQL文(from句内にselect文を作成)
select ( sum(▲▲.カラム名1), sum(▲▲.カラム名2), sum(××.カラム名), count(apps.id) ) from (select id, user_id, count(apps.id) from apps where user_id = 2) as apps inner join inner join users on apps.user_id = users.id inner join ▲▲ on apps.id = ▲▲.app_id inner join ×× on apps.id = ××.app_id;
sumの中が期待される値よりも大きくなってしまう。
SQL文(カラムごとにdistinct生成)
select ( sum(distinct ▲▲.カラム名1), sum(distinct ▲▲.カラム名2), sum(distinct ××.カラム名), count(apps.id) ) from (select id, user_id, count(apps.id) from apps where user_id = 2) as apps inner join inner join users on apps.user_id = users.id inner join ▲▲ on apps.id = ▲▲.app_id inner join ×× on apps.id = ××.app_id;
sumの中が期待される値よりも小さくなってしまう。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/25 10:07