MySQL 简单case语句范围查询表达式值该怎么写成范围形式
时间: 2023-07-15 17:10:54 浏览: 119
假设你要进行范围查询的列名为`score`,查询条件为:当`score`为1、2、3时,返回值为“不及格”;当`score`为4或5时,返回值为“及格”;当`score`为6或7时,返回值为“中等”;当`score`为8或9时,返回值为“良好”;当`score`为10时,返回值为“优秀”。
你可以使用以下SQL语句进行范围查询:
```
SELECT
score,
CASE
WHEN score IN (1,2,3) THEN '不及格'
WHEN score IN (4,5) THEN '及格'
WHEN score IN (6,7) THEN '中等'
WHEN score IN (8,9) THEN '良好'
WHEN score = 10 THEN '优秀'
END AS score_level
FROM
your_table;
```
其中,`IN`关键字可以用来表示多个值之间的范围。这里使用了`CASE`语句将查询结果按照条件进行分类,将`score`的取值范围映射为对应的等级。最后使用`AS`关键字为查询结果重命名为`score_level`。
相关问题
MySQL 简单case语句范围查询表达式值该怎么写成区间形式
如果你想在 MySQL 中使用简单 CASE 语句进行区间形式的范围查询,可以使用 BETWEEN 和 AND 运算符来表示区间。例如:
```
SELECT
CASE
WHEN age BETWEEN 0 AND 18 THEN '未成年人'
WHEN age BETWEEN 19 AND 40 THEN '青年人'
WHEN age BETWEEN 41 AND 60 THEN '中年人'
ELSE '老年人'
END AS age_group
FROM users;
```
在上面的例子中,我们使用了 BETWEEN 和 AND 运算符来表示年龄的区间,根据不同的年龄段返回不同的分类标签。注意,BETWEEN 运算符是包含边界的,如果你想排除某个边界,可以使用 < 或 > 运算符。
mysql的case语句
MySQL的CASE语句是一种条件语句,用于根据给定的条件执行不同的操作。它有两种形式:简单CASE语句和可搜索CASE语句。
1. 简单CASE语句
简单CASE语句的语法如下:
```
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE default_result
END
```
其中,expression是要比较的表达式,value1、value2等是要比较的值,result1、result2等是对应的结果,default_result是当没有匹配的值时返回的默认结果。
举个例子,假设有一个名为tbl_test_campus的表,其中有一个名为campus_tp的字段,它的值为0或1,分别表示大学和中小幼。我们可以使用简单CASE语句将其转化为具体含义,SQL语句如下:
```
SELECT campus_tp, CASE campus_tp
WHEN "0" THEN "大学"
WHEN "1" THEN "中小幼"
ELSE ""
END AS "校园类别"
FROM tbl_test_campus;
```
上述SQL语句将campus_tp字段的值与0和1进行比较,如果是0则返回“大学”,如果是1则返回“中小幼”,否则返回空字符串。执行结果如下:
```
+-----------+--------------+
| campus_tp | 校园类别 |
+-----------+--------------+
| 0 | 大学 |
| 0 | 大学 |
| 1 | 中小幼 |
| | |
+-----------+--------------+
4 rows in set (0.00 sec)
```
2. 可搜索CASE语句
可搜索CASE语句的语法如下:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
```
其中,condition1、condition2等是要比较的条件,result1、result2等是对应的结果,default_result是当没有匹配的条件时返回的默认结果。
举个例子,假设有一个名为tbl_test_score的表,其中有一个名为score的字段,我们可以使用可搜索CASE语句将其转化为成绩等级,SQL语句如下:
```
SELECT score,
CASE
WHEN score >= 90 THEN "优秀"
WHEN score >= 80 THEN "良好"
WHEN score >= 70 THEN "中等"
WHEN score >= 60 THEN "及格"
ELSE "不及格"
END AS "成绩等级"
FROM tbl_test_score;
```
上述SQL语句将score字段的值与一系列条件进行比较,如果满足条件则返回对应的成绩等级,否则返回“不及格”。执行结果如下:
```
+-------+--------+
| score | 成绩等级 |
+-------+--------+
| 85 | 良好 |
| 92 | 优秀 |
| 68 | 中等 |
| 55 | 不及格 |
+-------+--------+
4 rows in set (0.00 sec)
```
阅读全文
相关推荐
















