我有查询
SELECT all_users,
employed_users,
SUM(CASE WHEN (employment_one_terminated = 1 OR employment_two_terminated = 1) THEN 1 ELSE 0 END) AS unemployed_users
FROM users
WHERE status = 1
我在网页上添加了过滤器unemployed_min和unemployed_max数字,有没有办法在MySQL中过滤而不涉及PHP当你在页面上选择时说
unemployed_min = 1
unemployed_max = 5
当我做的时候
SELECT all_users,
employed_users,
SUM(CASE WHEN (employment_one_terminated = 1 OR employment_two_terminated = 1) THEN 1 ELSE 0 END) AS unemployed_users
FROM users
WHERE status = 1
AND unemployed_users > 1 AND unemployed_users < 5
或
SELECT all_users,
employed_users,
SUM(CASE WHEN (employment_one_terminated = 1 OR employment_two_terminated = 1) THEN 1 ELSE 0 END) AS unemployed_users
FROM users
WHERE status = 1
AND SUM(CASE WHEN (employment_one_terminated = 1 OR employment_two_terminated = 1) THEN 1 ELSE 0 END) > 1
AND SUM(CASE WHEN (employment_one_terminated = 1 OR employment_two_terminated = 1) THEN 1 ELSE 0 END) < 5
不起作用
修改 它说“无效使用群组功能”但是我不使用群组声明
答案 0 :(得分:0)
您正在寻找having
子句,因为您想要对聚合表达式进行过滤:
SELECT all_users,
employment_terminated,
unemployment_collected,
SUM(CASE WHEN (employment_one_terminated = 1 OR employment_two_terminated = 1) THEN 1 ELSE 0 END) AS unemployed_users
FROM users
WHERE status = 1
HAVING unemployed_users > 1 AND unemployed_users < 5;
答案 1 :(得分:0)
您的查询存在严重的分组问题。您正在使用聚合函数,而不是在选择一些字段时按任何字段进行分组。这意味着您只会在all_users
和employed_users
中获得包含不可预测值的一行。
首先,您必须定义正确的分组(可能是这个?)
GROUP BY all_users, employed_users
然后,如果您需要过滤组,可以使用HAVING
子句:
HAVING unemployed_users > 1 AND unemployed_users < 5
您也可以通过这种方式简化SUM
:
SUM(employment_one_terminated = 1 OR employment_two_terminated = 1)
如果这些是布尔值,您甚至可以删除= 1
。
最终查询应该与此非常相似:
SELECT all_users, employed_users,
SUM(employment_one_terminated OR employment_two_terminated) AS unemployed_users
FROM users
WHERE status = 1
GROUP BY all_users, employed_users
HAVING unemployed_users > 1 AND unemployed_users < 5