我有表table_one, table_two, table_three, table_four
所有結構大致相同。 它有列id, name, status, user_id
。來自多個表的MySQL請求數
i.g.除了table_four之外,我在每個表中多次使用約翰用戶user_id 345
。 status
對於一些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
的只有兩條記錄。
什麼是不工作?另外:你的意思是在'LEFT JOIN'中使用'= tbl_resume.candidate_id'嗎? – Edward 2012-02-28 20:17:24
對不起,我現在修好了。 – JohnA 2012-02-29 18:19:37
每個表都以自己的鍵連接到自己,這是沒有意義的。我的想法是你從table_one到table_two,table_two到table_three,table_three到table_four。請糾正我,如果我錯了 – 2012-02-29 18:49:31