SELECT
( SELECT
SUM(IF(status = 'Active', 1, 0)) AS `univ_active`,
SUM(IF(status = 'Inactive', 1, 0)) AS 'univ_inactive',
Count(*)
FROM online_university
)
AS tot_university,
( SELECT
SUM(IF(status = 'Active', 1,0)) AS `user_active`,
SUM(IF(status = 'Inactive', 1,0)) AS 'user_inactive'
Count(*)
FROM online_register_user)
AS tot_users
结果必须是
univ_active=4 univ_inactive=2 tot_university=6
user_active=10 user_inactive=3 tot_users = 13
我怎么能得到这个?上面的查询返回ERROR:操作数应包含1列
这将从表中返回Active,Inactive,Total记录的所有表中为项目准备报告。如果这种方法错了那么我应该用什么?任何建议。
答案 0 :(得分:3)
子查询只能返回一列。您需要在单个子查询中执行多个子查询,连接或廉价的concat hack(CONCAT_WS(',', SUM(IF(status = 'Active', 1,0)), SUM(IF(status = 'Inactive', 1,0))
)。
答案 1 :(得分:2)
如错误所示,您正在选择一个返回两列的子查询。
SELECT (one_thing, another_thing) AS combined_thing
SQL中不存在。您必须自己放置每个子查询:
SELECT (
SELECT SUM(IF(status='Active', 1, 0)) FROM online_university
) AS univ_active, (
SELECT SUM(IF(status='Inactive', 1, 0)) FROM online_university
) AS univ_inactive, (
SELECT SUM(IF(status='Active' OR status='Inactive', 1, 0)) FROM online_university
) AS tot_university, (
SELECT SUM(IF(status='Active', 1, 0)) FROM online_register_user
) AS user_active, (
-- and so on
但是,在单个查询中完成所有这些操作确实没有任何好处。更容易说:
SELECT COUNT(*) FROM online_university WHERE status='Active'; -- univ_active
SELECT COUNT(*) FROM online_university WHERE status='Inactive'; -- univ_inactive
SELECT COUNT(*) FROM online_university; -- tot_university
SELECT COUNT(*) FROM online_register_user WHERE status='Active'; -- user_active
-- and so on
然后将这些结果一起呈现在应用程序层中。 WHERE子句更快,可以使用正确的索引,而SUM / IF等计算表达式则不能。
更简单:
SELECT status, COUNT(*) FROM online_university GROUP BY status;
SELECT status, COUNT(*) FROM online_register_user GROUP BY status;
答案 2 :(得分:1)
通过按照我刚才在问题中所做的那样布局查询,很明显,别名tot_university,例如将与两列相关联,这是不可能的......
除了这个语法/逻辑错误之外,整个查询的结构似乎很差,无法产生所需的结果。
它看起来非常像家庭作业或自我分配的学习,所以我不会用现成的查询破坏它,而是这里有一些提示。
答案 3 :(得分:1)
正如BipedalShark所说,你的查询应该有1列,现在它们有2列。但除此之外,你应该考虑使用count(*)和where子句。所以它应该是这样的:
select
(select count(*) from online_university where status = 'Active') as univ_active,
(select count(*) from online_university where status = 'Inactive') as univ_inactive,
(select count(*) from online_register_user where status = 'Active') as user_active,
(select count(*) from online_register_user where status = 'Active') as user_inactive