数据库每日一题---第13天:寻找病患

283 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情

一、问题描述

患者信息表: Patients

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| patient_id   | int     |
| patient_name | varchar |
| conditions   | varchar |
+--------------+---------+
patient_id (患者 ID)是该表的主键。
'conditions' (疾病)包含 0 个或以上的疾病代码,以空格分隔。
这个表包含医院中患者的信息。

写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1 。

任意顺序 返回结果表。

查询结果格式如下示例所示。

题目链接:寻找病患

二、题目要求

样例

输入:
Patients表:
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 1          | Daniel       | YFEV COUGH   |
| 2          | Alice        |              |
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 |
| 5          | Alain        | DIAB201      |
+------------+--------------+--------------+
输出:
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 | 
+------------+--------------+--------------+
解释:Bob 和 George 都患有代码以 DIAB1 开头的疾病。

考察

1.模糊查询
2.建议用时10~25min

三、问题分析

1.模糊查询

这一题本质上就是一道条件查询,要求我们查询以前缀 DIAB1开头的患者所有信息。

模糊查询一般使用like,这一题我们要注意不能只使用第一个单词进行模糊查询,后面第二个字母也需要。

所以,对于模糊查询的代码为:

where conditions like 'DIAB1%'  or conditions like '% DIAB1%'

2.正则表达式

我们可以直接使用SQL里面的正则表达式,来匹配开头的字母。

where conditions rlike '^DIAB1|\\sDIAB1'

其中,^DIAB1代表开头第一个,而\\sDIAB1代表空格之后的第一个匹配的单词。更多关于正则表达式的教程可以参考:菜鸟教程

四、编码实现

1.模糊查询

select*
from Patients
where conditions like 'DIAB1%'  or conditions like '% DIAB1%'

2.正则表达式

select * 
from Patients 
where conditions rlike '^DIAB1|\\sDIAB1'

五、测试结果

1.png

2.png

19.png