2014-01-16 88 views
0

我有這個疑問從兩個表中獲取信息:如何在同一個查詢中使用部分sql查詢?

SELECT u.username, u.id, 
      SUM(t.result = 1) AS winnings, 
      SUM(t.result = 2) AS loses 
    FROM users u 
    LEFT JOIN tahminler t ON u.id = t.user_id 
    GROUP BY u.id 

我想comments_no從另一個表中的每個用戶;是這樣的:

SELECT u.username, u.id, 
      SUM(t.result = 1) AS winnings, 
      SUM(t.result = 2) AS loses, 
      f1.comments_no 
    FROM users u 
    LEFT JOIN tahminler t ON u.id = t.user_id 
    INNER JOIN (select count(distinct match_static_id) as comments_no,user_id from comments where user_id = "here is my problem") 
    GROUP BY u.id 

是否有可能,但u.id在where user_id = u.id價值。 簡要說明如何在查詢中獲取每個用戶的comments_no。?

回答

0

在子查詢中使用GROUP BY: -

SELECT u.username, u.id, 
      SUM(t.result = 1) AS winnings, 
      SUM(t.result = 2) AS loses, 
      f1.comments_no 
    FROM users u 
    LEFT JOIN tahminler t ON u.id = t.user_id 
    INNER JOIN (select user_id, count(distinct match_static_id) as comments_no from comments GROUP BY user_id) f1 
    ON u.id = f1.user_id 
    GROUP BY u.id 
相關問題