2010-11-11 77 views
1

有一個稱爲表1的假想表,用列:MySQL的 - 指望不同的條件不同的領域中一個連接表

  • ID
  • 條件1
  • 條件2
  • joinable_key

還有一個Main_Table,其ID與第一個中的joinable_key相對應。

我想以這樣一種方式加入他們,我可以根據條件1和條件2分別計算Table1的行數 - 也就是說,我希望能夠執行「count(Table1.condition1)作爲first_condition,在select查詢上計數(Table1.condtion2)作爲second_condition「。

查詢大概會是這個樣子:

SELECT Main_Table.some_column, COUNT(Table1.condition1) AS first_condition, COUNT(Table1.condtion2) AS second_condition 
FROM Main_Table 
LEFT JOIN Table1 AS T1 on (T1.joinable_key = Main_Table.id AND T1.condition1 = 'something') 
LEFT JOIN Table1 AS T2 on (T2.joinable_key = Main_Table.id AND T2.condition2 = 'something else') 
GROUP BY (Main_Table.id) 

當此執行,但是,這兩個計數結果是相等的,並且相互實際上繁殖。 必須將所有結果包含在最終輸出中 - 包括那些沒有Table1中任何條目的結果 - 也就是說,如果Table1中沒有行,並且joinable_key等於Main_Table.id,那麼它也需要包含在內。

在任何人建議實際做兩個單獨的查詢並通過PHP處理它之前 - 我知道爲什麼以及如何完成它,但我的目標是確定這個多重計數是否可以在一箇中完成查詢。

謝謝

+0

[在一個查詢在MySQL計數多行(http://stackoverflow.com/questions/2957269/counting-multiple-rows-in-mysql-in-one-query) – Konerak 2010-11-11 10:57:14

回答

4
SELECT some_column, 
     (SELECT COUNT(1) 
      FROM Table1 
     WHERE mt.id = joinable_key 
      AND condition1 = 'something' 
     ) AS first_condition, 
     (SELECT COUNT(1) 
      FROM Table1 
     WHERE mt.id = joinable_key 
      AND condition2 = 'something else' 
     ) AS second_condition 
    FROM MainTable mt 
+0

這個子查詢解決方案是正確的,謝謝! – Swader 2011-04-23 16:34:23

0
SELECT Main_Table.some_column, 
     SUM(t1.condition1 = 'something') AS first_condition, 
     SUM(t1.condition2 = 'something_else') AS second_condition 
FROM Main_Table 
LEFT JOIN 
     Table1 AS t1 
ON  t1.joinable_key = Main_Table.id 
     AND 
     (
     t1.condition1 = 'something' 
     OR 
     t1.condition2 = 'something else' 
     ) 
GROUP BY 
     Main_Table.id 

如果同時condition1condition2是有選擇性的,這句法可能更有效:

SELECT Main_Table.some_column, 
     (
     SELECT COUNT(*) 
     FROM table1 t1 
     WHERE t1.joinable_key = main_table.id 
       AND t1.condition1 = 'something' 
     ), 
     (
     SELECT COUNT(*) 
     FROM table1 t1 
     WHERE t1.joinable_key = main_table.id 
       AND t1.condition2 = 'something_else' 
     ) 
FROM Main_Table 

你應該創建以下指標:

table1 (id, condition1) 
table1 (id, condition2) 

爲這個工作很快。

+0

我的可能重複對沒有及時回覆表示歉意。我會盡我所能,儘快對此進行正確測試。 – Swader 2010-11-13 16:01:15