2014-01-10 41 views
0

我有一個SQL查詢,從三個不同的表獲取信息如下:如何在同一個查詢中提及兩個聚合函數?

select users.username, users.id, users.avatar, users.daily_tahmin, users.alert, f1.comments_no, f2.tahmins_no, f3.monthly_tahmins_no from users LEFT join 
(SELECT count(comments) AS comments_no, user_id 
FROM comments 
    Where user_id = 12 
) AS f1 on users.id = f1.user_id left join 
(
    SELECT count(tahmin) AS tahmins_no, user_id 
    FROM tahminler 
    Where user_id = 12 
) AS f2 on users.id = f2.user_id left join 
(
    SELECT count(tahmin) AS monthly_tahmins_no, user_id, matches_of_comments.match_id 
    FROM tahminler 
    INNER JOIN matches_of_comments on tahminler.match_id = matches_of_comments.match_id 
    Where user_id = 12 AND (MONTH(STR_TO_DATE(matches_of_comments.match_date, '%d.%m.%Y')) = '01' AND YEAR(STR_TO_DATE(matches_of_comments.match_date, '%d.%m.%Y')) = '2014') 
) AS f3 on users.id = f3.user_id 
where users.id = 12 

,它提供了以下結果:

+------------+----+----------------+--------------+-------+-------------+------------+--------------------+ 
| username | id |  avatar  | daily_tahmin | alert | comments_no | tahmins_no | monthly_tahmins_no | 
+------------+----+----------------+--------------+-------+-------------+------------+--------------------+ 
| cold heart | 12 | 1389002263.jpg |   0 |  0 |   65 |  258 |     10 | 
+------------+----+----------------+--------------+-------+-------------+------------+--------------------+ 

後,我做了一些EXPLIAN前面的代碼未進行優化和我試圖優化它,我得到了下面的查詢:

SELECT m.*,count(comments.id) 
FROM comments 
JOIN 
(SELECT users.username, users.id, users.avatar, users.daily_tahmin, users.alert 
FROM users 
WHERE id=12)as m ON m.id = comments.user_id 

我的問題是,我不能讓(tahmins_no,monthly_tahmins_no)電子非常時間我將它們添加到查詢它給出了錯誤的結果我找不到一種方法來正確地將它們添加到查詢以優化的方式?我可以在這裏得到任何人的建議嗎?

回答

0

你簡化查詢:

select m.*, count(c.id) 
from comments c join 
    users m 
    on m.id = c.user_id 
where m.id = 12 
group by m.id; 

你應該能夠在每月的數量增加:

select m.*, count(c.id), f3.* 
from comments c join 
    users m 
    on m.id = c.user_id join 
    (select count(tahmin) AS monthly_tahmins_no, user_id, moc.match_id 
     from tahminler t join 
      matches_of_comments moc 
      on t.match_id = moc.match_id 
     Where user_id = 12 AND 
      MONTH(STR_TO_DATE(moc.match_date, '%d.%m.%Y')) = 1 AND 
      YEAR(STR_TO_DATE(moc.match_date, '%d.%m.%Y')) = 2014 
    ) f3 
    on f3.user_id = m.id 
where m.id = 12 
group by m.id; 

month()year()函數返回的數字,而不是字符串。我不明白爲什麼字段match_date會作爲字符串存儲 - 看起來像一個名字包含日期的列的愚蠢選擇。

+0

它正在工作,但tahmins_no沒有添加(我的意思是整個tahmin_no不只是每月) – Basel

+0

你必須在另一個子查詢中計算並將其添加到查詢中。 –

相關問題