2009-05-13 5 views
0

私は、SQLクエリを持っている:私のSQLステートメントは、1つのSQLステートメント内の異種テーブルと異なるフィールド数になるのはなぜですか?

SELECT 
    e.name as estate_name 
    , g.name as governing_body 
    , count(s.id) as total_stands 
    , count(sp.id) as service_providers 
FROM estates e 
    LEFT JOIN governing_bodies  
     ON e.governing_body_id = g.id 
    LEFT JOIN stands s 
     ON s.estate_id = e.id 
    LEFT JOIN services sp 
     ON sp.estate_id = e.id 
GROUP BY e.id 

私のカウントがお互いを掛けるように思え。最初のカウントが3で2番目のカウントが10の場合、service_providersフィールドとtotal_standsフィールドの結果は30になります。

私は間違っていますか?

答えて

1

count()には、あなたのグループで見つかった行数が表示されます。不動産をグループ化しているので、不動産に加入する行の数がカウントされます。結合によって行の数が増えますので、正しい数と同様に3 x 10 = 30の音が得られます。 GROUP BYを使わずにクエリを実行すると、何が起きているのかを確認できます。それは次のようになります修正する

一つの方法:

SELECT 
    e.name as estate_name, 
    g.name as governing_body, 
    IsNull(stand_count.total,0) as stand_count, 
    IsNull(service_count.total,0) as service_count 
FROM estates e 
LEFT JOIN governing_bodies g on e.governing_body_id = g.id 
LEFT JOIN (
    select estate_id, total = count(*) from stands group by estate_id 
) stand_count on stand_count.estate_id = e.id 
LEFT JOIN (
    select estate_id, total = count(*) from services group by estate_id 
) service_count on service_count.estate_id = e.id 
GROUP BY 
    e.name, 
    g.name, 
    IsNull(stand_count.total,0), 
    IsNull(service_count.total,0) 
:JOIN構文を持つ、より複雑な代替手段として、

SELECT 
    e.name as estate_name 
    , g.name as governing_body 
    , count(distinct s.id) as total_stands 
    , count(distinct sp.id) as service_providers 
FROM estates e 
    LEFT JOIN governing_bodies  
     ON e.governing_body_id = g.id 
    LEFT JOIN stands s 
     ON s.estate_id = e.id 
    LEFT JOIN services sp 
     ON sp.estate_id = e.id 
GROUP BY e.id, g.name 

または:

SELECT 
    e.name as estate_name, 
    g.name as governing_body, 
    (select count(*) from stands s where s.estate_id = e.id) as stands, 
    (select count(*) from services sp where sp.estate_id = e.id) as services 
FROM estates e 
LEFT JOIN governing_bodies g on e.governing_body_id = g.id 

はアレックスマルテッリの有益な答えを書きます
+0

大変お世話になりました。 –

1

COUNT(blah)のコンストラクトをに変更すると3210?

+0

+1クールはあなたがそれを行うことができるか分からなかった! – Andomar

関連する問題