假设我有一个这样的 SQL 查询
SELECT player_name,weight,
CASE WHEN weight > 250 THEN 'over 250'
WHEN weight > 200 THEN '201-250'
WHEN weight > 175 THEN '176-200'
ELSE '' END AS weight_group
FROM benn.college_football_players
我想在不打扰 ELSE ' ' 的情况下显示不为空的记录(权重不为空),因为这会在查询中导致很多不必要的错误,是否有解决方法? 我用过
where weight_group is not null
在最后,但它抛出一个错误作为“无效标识符”
除了将整个选择条件放在另一个选择语句中之外,还有其他解决方法吗?
最佳答案
NULL
不等于 MySQL
中的''
。 NULL
表示无数据
,empty string
表示空字符串
,它们是两个不同的东西。
需要根据空字符串来过滤数据
where weight_group != '';
现在您可以通过多种方式实现预期的结果。
<强>1。使用子查询
SELECT *
FROM (SELECT player_name,weight,
CASE
WHEN weight > 250 THEN 'over 250'
WHEN weight > 200 THEN '201-250'
WHEN weight > 175 THEN '176-200'
ELSE ''
END AS weight_group
FROM benn.college_football_players) AS t
WHERE weight_group != '';
<强>2。使用分组依据
SELECT player_name,weight,
CASE WHEN weight > 250 THEN 'over 250'
WHEN weight > 200 THEN '201-250'
WHEN weight > 175 THEN '176-200'
ELSE ''
END AS weight_group
FROM benn.college_football_players
GROUP BY weight_group, weight, player_name
HAVING weight_group != '';
关于mysql - 使用 'END as' 语句从动态生成的列名中选择不为空的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499443/