我正在为我的数据库构建一般统计信息。
我想知道如何联合这么多SELECTS,以便我得到1行不同列的结果。
SELECT COUNT(*) AS total_users FROM users;
SELECT COUNT(*) AS total_verified FROM users WHERE verified = 1;
SELECT COUNT(*) AS total_passed_tut FROM users WHERE level = 3;
SELECT COUNT(*) AS total_private FROM users WHERE privacy = 0;
SELECT COUNT(*) AS total_friends_only FROM users WHERE privacy = 2;
SELECT COUNT(*) AS total_public FROM users WHERE privacy = 3;
这样做有意义吗?或者我应该做单独的查询并保存到数组1?
答案 0 :(得分:3)
您可以在一个查询中执行此操作
SELECT COUNT(*) AS total_users,
sum(verified = 1) as total_verified,
sum(level = 3) as total_passed_tut,
sum(privacy = 0) as total_private,
sum(privacy = 2) as total_friends_only,
sum(privacy = 3) as total_public
FROM users;
答案 1 :(得分:0)
SELECT (SELECT COUNT(*) AS total_users FROM users) as `total_users`,
SELECT (SELECT COUNT(*) AS total_verified FROM users WHERE verified = 1) as `total_verified`,
SELECT (SELECT COUNT(*) AS total_passed_tut FROM users WHERE level = 3) as `total_passed_tut`,
SELECT (SELECT COUNT(*) AS total_private FROM users WHERE privacy = 0) as `total_private`,
SELECT (SELECT COUNT(*) AS total_friends_only FROM users WHERE privacy = 2) as `total_friends_only`,
SELECT (SELECT COUNT(*) AS total_public FROM users WHERE privacy = 3) as `total_public`
FROM dual