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)電子非常時間我將它們添加到查詢它給出了錯誤的結果我找不到一種方法來正確地將它們添加到查詢以優化的方式?我可以在這裏得到任何人的建議嗎?
它正在工作,但tahmins_no沒有添加(我的意思是整個tahmin_no不只是每月) – Basel
你必須在另一個子查詢中計算並將其添加到查詢中。 –