2017-10-11 54 views
1

我有4個表如下 -加盟條件是怎麼了?

tbl_confession -

Confession_id User_id title message 
1    1  new foo 
2    1  abcd yes 
4    1  bar no 

tbl_comment -

Comment_id user_id confession_id message 
1   2  1    foobar 
2   2  1    barfoo 

tbl_confessionlike -

id confession_id user_id 
1 1    1 
2 1    2 
3 2    2 

tbl_confessionview -

id user_id confession_id 
1 1  1 

預期的結果應該是 -

ConfressionId title message total_comments total_likes total_views 
1    new foo  2    2   1 
2    abcd yes  0    1   0 
4    bar no  0    0   0 

我使用來實現上述結果的查詢 -

SELECT c.confession_id 
     ,c.title 
     ,c.message 
     ,COUNT(co.comment_id) 
     ,COUNT(cl.id) 
     ,COUNT(cv.ID) 
FROM tbl_confession c 
LEFT JOIN tbl_comment co on c.confession_id = co.confession_id 
LEFT JOIN tbl_confessionlike cl on c.confession_id = cl.confession_id 
LEFT JOIN tbl_confessionview cv on c.confession_id = cv.confession_id 
GROUP BY c.confession_id 
     ,c.title 
     ,c.message 

輸出結果 -

ConfressionId title message total_comments total_likes total_views 
1    new foo  4    4   4 
2    abcd yes  0    1   0 
4    bar no  0    0   0 

但是給我計數爲4而不是2.此外,如果我想看到每個用戶相同的結果它仍然是相同的user_id = 1但爲其他用戶的空值。我無法解決錯誤。提前致謝。

+1

這是給你數4?哪個記錄在哪? – JNevill

+5

WFM http://sqlfiddle.com/#!9/45f718/1 – orhtej2

+0

參見:[?我爲什麼要爲了什麼,在我看來是一個非常簡單的SQL查詢提供MCVE(HTTPS://meta.stackoverflow。 COM /問題/ 333952 /爲什麼,應該-I-提供-AN-MCVE換什麼,似乎對我將要-A-極簡單的SQL查詢) – Strawberry

回答

0

我想是因爲你是將數據從表tbl_confession分組你有問題。在您的例子有2評論,喜歡2,和產生2 * 2 * 1 = 4記錄1個視圖,當您使用在主查詢c.confession_id集團count()將返回4.我會snuggest到組記錄在每個部分表的再加入他們的主要查詢,像這樣的東西:

 SELECT c.confession_id, 
      c.title, 
      c.message, 
      comment.total_comment, 
      likes.total_likes, 
      views.totla_views 
    FROM tbl_confession c 
    INNER JOIN 
     (SELECT 
      confession_id, 
      COUNT(Comment_id) AS total_comment 
      FROM tbl_comment 
      GROUP BY confession_id 
     ) 
     AS comment ON comment.confession_id = c.confession_id 
    INNER JOIN 
     (SELECT 
      confession_id, 
      COUNT(id) as total_likes 
      FROM tbl_confessionlike 
      GROUP BY confession_id 
     ) 
     AS likes ON likes.confession_id = c.confession_id 
    INNER JOIN 
     (SELECT 
      confession_id, 
      COUNT(id) AS totla_views 
      FROM tbl_confessionview 
      GROUP BY confession_id 
     ) 
     AS views ON views.confession_id = c.confession_id 
    WHERE c.user_id = some_id 
+0

我剛纔達到同樣的效果通過將不同的計數函數放在一起,但真正的挑戰是通過在where子句中傳遞user_id來獲得每個用戶相同的期望列。 –

+0

我在此發佈的預期結果是所有表格的總數,與用戶無關。如果我想看到特定用戶的相同結果(假設user_id = 1),我需要將該用戶傳遞到cond。傳遞user_id = 1會給我相同的結果,而對於其他人則是null。請讓我知道你是否需要更多的細節。 –

+0

這只是示例數據。我不能在這裏發佈真正的表格。實際的表格比這個多得多,他們確實有來自user_id = 1以外的用戶的口供。 –