1527. 患某种疾病的患者
1527. 患某种疾病的患者
题目: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 开头的疾病。
题解
疾病代码以空格分隔。第一条 LIKE 检查字段开头,第二条检查任意空格之后的位置。两者都从代码的起点匹配 DIAB1,避免把位于其他代码内部的字符误判为前缀。
1
2
3
4
5
6
SELECT patient_id,
patient_name,
conditions
FROM Patients
WHERE conditions LIKE 'DIAB1%'
OR conditions LIKE '% DIAB1%';
本地复现
环境为 MySQL 8.4.8,使用默认 sql_mode(含 ONLY_FULL_GROUP_BY)。以下语句按示例 1 建表并插入数据:
1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE Patients (
patient_id INT,
patient_name VARCHAR(255),
conditions VARCHAR(255)
);
INSERT INTO Patients (patient_id, patient_name, conditions) VALUES
(1, 'Daniel', 'YFEV COUGH'),
(2, 'Alice', ''),
(3, 'Bob', 'DIAB100 MYOP'),
(4, 'George', 'ACNE DIAB100'),
(5, 'Alain', 'DIAB201');
运行结果:
1
2
3
4
5
6
+------------+--------------+--------------+
| patient_id | patient_name | conditions |
+------------+--------------+--------------+
| 3 | Bob | DIAB100 MYOP |
| 4 | George | ACNE DIAB100 |
+------------+--------------+--------------+
本文由作者按照 CC BY 4.0 进行授权
