2014-01-10 39 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

你必须在另一个子查询中计算并将其添加到查询中。 –

相关问题