2012-02-28 85 views
0

我有表table_one, table_two, table_three, table_four所有結構大致相同。 它有列id, name, status, user_id來自多個表的MySQL請求數

i.g.除了table_four之外,我在每個表中多次使用約翰用戶user_id 345status對於一些entrys是1和其他條目的是0

現在我需要計數與一個查詢多少次這個用戶的狀態是每個表中1。

所以我:

SELECT table_one.user_id, 
    SUM(CASE WHEN table_one.status = 1 THEN 1 ELSE 0 END) AS count_tblone 
    SUM(CASE WHEN table_two.status = 1 THEN 1 ELSE 0 END) AS count_tbltwo 
    SUM(CASE WHEN table_three.status = 1 THEN 1 ELSE 0 END) AS count_tblthree 
    SUM(CASE WHEN table_four.status = 1 THEN 1 ELSE 0 END) AS count_tblfour 
FROM table_one 
    LEFT JOIN table_one ON table_one.user_id = table_one.user_id 
    LEFT JOIN table_two ON table_two.user_id = table_one.user_id 
    LEFT JOIN table_three ON table_three.user_id = table_one.user_id 
    LEFT JOIN table_four ON table_four.user_id = table_one.user_id 

WHERE tbl_one.user_id = 345 

問題是,請求輸出4,0,0,0,當它應該是2,1,1,0

如果我剛離開SUM(CASE WHEN table_one.status = 1 THEN 1 ELSE 0 END) AS count_tblone - count_tblone將等於4,即使在table_one - status字段等於1,用戶345的只有兩條記錄。

+1

什麼是不工作?另外:你的意思是在'LEFT JOIN'中使用'= tbl_resume.candidate_id'嗎? – Edward 2012-02-28 20:17:24

+0

對不起,我現在修好了。 – JohnA 2012-02-29 18:19:37

+0

每個表都以自己的鍵連接到自己,這是沒有意義的。我的想法是你從table_one到table_two,table_two到table_three,table_three到table_four。請糾正我,如果我錯了 – 2012-02-29 18:49:31

回答

0

這是更多的打字,但我建議UNION,,特別是如果用戶可能不在table_one

SELECT 
    SUM(count_tblone) AS count_tblone, 
    SUM(count_tbltwo) AS count_tbltwo, 
    SUM(count_tblthree) AS count_tblthree, 
    SUM(count_tblfour) AS count_tblfour 
FROM (
    SELECT 
     SUM(CASE WHEN table_one.status = 1 THEN 1 ELSE 0 END) AS count_tblone, 
     0 AS count_tbltwo, 
     0 AS count_tblthree, 
     0 AS count_tblfour 
    FROM table_one 
    WHERE tbl_one.user_id = 345 
    UNION 
    SELECT 
     0 AS count_tblone, 
     SUM(CASE WHEN table_two.status = 1 THEN 1 ELSE 0 END) AS count_tbltwo, 
     0 AS count_tblthree, 
     0 AS count_tblfour 
    FROM table_two 
    WHERE tbl_one.user_id = 345 
    UNION 

...表3和表4 ...

) AS tblMyUnionedTables 
+0

此外,如果將結果檢索爲4個一列的行而不是1個四列的行,那麼您可以取出'0 AS count_tbl ...'項,並且您可以從中得到結果現在是上述答案中的一個子表。請注意,在這種情況下,您將需要'UNION ALL'來代替'UNION'。同樣在這種情況下,你可以在where子句中添加'status = 1'並獲得計數。 – 2012-02-29 20:06:07