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

时间:2018-12-17 15:43:13

标签: mysql sql eloquent

让我们考虑一下,我有一个名为 Citizens 的表,其中包含以下字段和值:

| 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  |

2 个答案:

答案 0 :(得分:6)

您可以使用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);

第二种方法的一个主要可能优点是可以引入索引策略。

答案 1 :(得分:4)

我将使用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 );