跳转至

1527. 患某种疾病的患者

题目描述

患者信息表: Patients

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

 

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

任意顺序 返回结果表。

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

 

示例 1:

输入:
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 开头的疾病。

解法

方法一

思考

要找出病情列表中含有 \(DIAB1\) 前缀代码的患者。病情字段以空格分隔多个代码,直接用无边界的 \(LIKE\ \%DIAB1\%\) 会把 \(DIAB10\) 一类代码误收入。

代码若出现在串首,形态为 \(DIAB1\%\);若出现在中间,其前必有空格,形态为 \(\%\ DIAB1\%\)。两条前缀条件取或,即可在不误伤更长代码的前提下筛出目标行。

1
2
3
4
5
6
SELECT
    patient_id,
    patient_name,
    conditions
FROM patients
WHERE conditions LIKE 'DIAB1%' OR conditions LIKE '% DIAB1%';

评论