Mysql - 无法将变量传递给子查询

时间:2013-02-02 13:04:22

标签: mysql sql subquery

这是我的问题:

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 

问题是@UserID未传递给子查询

2 个答案:

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

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