显示在选定字段中匹配的条件值的位置

m528fe3b  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(237)

假设我有一个名为citilities的表,其中包含以下字段和值:

| ID | Name   | Age |
|----|:------:|---: |
| 1  | King   | 60  |
| 2  | Queen  | 50  |
| 3  | Prince | 25  |

如果我想显示年龄在“50到100”之间的公民和其他年龄在“5到30”之间的公民,我可以使用这样一个简单的where条件:

SELECT * FROM Citizens WHERE (Age BETWEEN 5 AND 30 ) OR (Age BETWEEN 50 AND 100 );

但是,问题来了:如何在符合条件的每一行旁边显示最小和最大请求的年龄来获得这样的结果?

| ID | Name   | Age |INTERVAL|
|----|:------:|:---:|-------:|
| 1  | King   | 60  | 50-100 |
| 2  | Queen  | 50  | 50-100 |
| 3  | Prince | 25  |  5-30  |
zzlelutf

zzlelutf1#

我会用一个 CASE 声明:

SELECT
  id, name, age,
  case when age between 5 and 30 then '5-30' else '50-100' end as interval
FROM Citizens
WHERE (Age BETWEEN 5 AND 30 ) OR (Age BETWEEN 50 AND 100 );
jw5wzhpr

jw5wzhpr2#

你需要一个 CASE 表达式:

SELECT Id, Name, Age,
    CASE WHEN Age BETWEEN 5 AND 30 THEN '5-30'
         WHEN Age BETWEEN 50 AND 100 THEN '50-100'
         ELSE 'OTHER' END AS INTERVAL
FROM Citizens
WHERE (Age BETWEEN 5 AND 30) OR (Age BETWEEN 50 AND 100);

注意:我不确定您是否只想显示特定的年龄范围。如果是的话,那就留下你现在的工作 WHERE 条款完好无损。如果要包含所有数据,请删除 WHERE 条款。在这种情况下,不匹配的范围将报告为 OTHER .
另一种可能扩展得更好的方法是使用间隔表:

start | end | interval
5     | 30  | 5-30
50    | 100 | 50-100

然后连接到此表以引入间隔标签:

SELECT c.Id, c.Name, c.Age, i.interval
FROM Citizens c
INNER JOIN interval i
    ON c.Age BETWEEN i.start AND i.end
WHERE (c.Age BETWEEN 5 AND 30) OR (c.Age BETWEEN 50 AND 100);

第二种方法的一个主要优点是,它可能引入指数策略。

相关问题