2011-07-24 26 views
1

我有以下的疑問 -左加入乘值

SELECT COUNT(capture_id) as count_captures 
    FROM captures 
WHERE user_id = 9 

...返回5

SELECT COUNT(id) as count_items 
    FROM items 
WHERE creator_user_id = 9 

...返回22

我嘗試下面的查詢 -

SELECT COUNT(capture_id) as count_captures, 
      COUNT(items.id) as count_items 
    FROM captures 
LEFT JOIN items ON captures.user_id = items.creator_user_id 
    WHERE user_id = 9 

...但它返回兩個co列均以110爲值。我想要一列5,另一列22。我究竟做錯了什麼?

回答

3

我下意識是一個子查詢:

select count(capture_id) as count_captures, 
    (select count(id) as count_items 
     from items i where i.creator_user_id = captures.user_id) as count_items 
from captures 
where user_id = 9 

我真的不知道你能做些什麼來避免這種情況。你看到了預期(通常是期望的行爲)。

當然,如果你知道ID在這兩個不會重複自己,你可以使用不同的:

SELECT COUNT(DISTINCT capture_id) as count_captures, 
     COUNT(DISTINCT items.id) as count_items 
FROM captures 
LEFT JOIN items ON captures.user_id = items.creator_user_id 
    WHERE user_id = 9 
+0

我一直都知道我可以跟一個子查詢,但你的第二個例子完美地工作。 – scott

1

你總是可以聯合的結果(警告,未經測試):

SELECT SUM(sub.count_captures), SUM(sub.count_items) 
FROM (SELECT COUNT(capture_id) as count_captures, 0 as count_items 
from captures where user_id = 9 
UNION 
SELECT 0 as count_captures, count(id) as count_items 
from items where creator_user = 9) sub 
+0

導致返回兩行。無論如何,它可能只是一個? – scott

+0

編輯我的答案,用子查詢聚合兩行 – Gunny

2

左連接返回每個行的左表中的結果相匹配的右表的每一行。由於你所有的id都是相同的,所以產生表的笛卡爾積。 (5 * 22 = 110)。

預計會發生這種情況。

+0

我明白爲什麼會發生這種情況。我想知道是否有這種情況發生?我只需要做多個查詢來獲得我想要的結果? – scott

+0

@scott:是的,這兩個查詢在兩個不同的表中搜索,因此需要兩個查詢。當然,有兩種方法可以將兩者合併爲一個查詢(使用兩個子查詢)。但是'JOIN'在這裏不是一個好方法。 –

1

另一種方式來兩(貌似不相關)的查詢合併爲一個:

SELECT 
    (SELECT COUNT(capture_id) 
     FROM captures 
     WHERE user_id = 9 
    ) 
    AS count_captures 

    , (SELECT COUNT(id) 
     FROM items 
     WHERE creator_user_id = 9 
    ) 
    AS count_items 

在這些情況下,確實不需要子查詢或JOIN。雖然優化器可能足夠聰明,但我不會試圖混淆他。