4

这是我的查询:

SELECT user.*, @UserID:=user.uid,
    (SELECT count(c1) FROM (
    SELECT COUNT(*) AS c1 FROM user_group
    WHERE user_group.uid=@UserID
    GROUP BY user_group.uid
) x1) AS x2

FROM user 

问题是@UserIDin 没有传递给子查询

4

2 回答 2

4

为什么要在那里传递变量?像这样直接使用外部表引用。

SELECT user.*, 
(SELECT COUNT(*) AS c1 FROM user_group
WHERE user_group.uid=user.uid
GROUP BY user_group.uid) AS GroupCount
FROM user;
于 2013-02-02T13:07:12.947 回答
2

如何使用JOIN?我认为结果与您想要的相同。我猜你想得到用户拥有的组总数。正确的?

SELECT  a.*, 
        COALESCE(b.totalCount, 0) totalCount,
        COALESCE(b.totalType, 0) totalType
FROM    user a
        LEFT JOIN
        (
            SELECT  uid, 
                    COUNT(*) totalCount, 
                    COUNT(DISTINCT type) totalType
            FROM    user_Group 
            GROUP BY uid
        ) b ON a.uid = b.uid
于 2013-02-02T13:08:21.443 回答