仅使用下users
表的每个用户ID总数总计的客户数:
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(u.clientid) ClientCount
FROM users u
WHERE u.active = 1
GROUP BY u.id WITH ROLLUP;
如果客户表已删除记录,请执行以下操作:
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(c.id) ClientCount
FROM users u INNER JOIN clients c
ON u.clientid = c.id
WHERE u.active = 1
GROUP BY u.id WITH ROLLUP;
对于users
没有active
列的表:
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(u.clientid) ClientCount
FROM users u
GROUP BY u.id WITH ROLLUP;
要么
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(c.id) ClientCount
FROM users u INNER JOIN clients c
ON u.clientid = c.id
GROUP BY u.id WITH ROLLUP;
您将需要针对每个数据库和UNION ALL
结果运行这些查询。
如果您想利用INFORMATION_SCHEMA数据库,那么这里是一个疯狂的猜测:
SELECT COUNT(1) INTO @hasactive
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'users'
AND column_name = 'active';
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(u.clientid) ClientCount
FROM users u
WHERE IF(@hasactive=1,u.active=1,1)=1
GROUP BY u.id WITH ROLLUP;
试试看 !!!