如何在同一个查询中使用部分sql查询?

时间:2014-01-16 09:09:06

标签: mysql sql query-optimization

我有这个查询来从两个表中获取信息:

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

是否可以使用where user_id = u.id中的u.id值。 简要说明如何在查询中为每个用户获取comments_no。

1 个答案:

答案 0 :(得分: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