1527. 患某种疾病的患者

123 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第23天,点击查看活动详情

一、题目

患者信息表: 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 。

按 任意顺序 返回结果表。

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

示例 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 | 
+------------+--------------+--------------+
解释:BobGeorge 都患有代码以 DIAB1 开头的疾病。

来源:力扣(LeetCode)

链接:leetcode.cn/problems/pa…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路

创建数据表

根据题意创建数据表,设置数据类型,并设置患者 ID为主键

CREATE TABLE Patients(
	patient_id INT PRIMARY KEY,
	patient_name VARCHAR(20),
	conditions VARCHAR(20)
);
INSERT INTO Patients VALUES
(1,"Daniel","YFEV COUGH"),
(2,"Alice",""),
(3,"Bob","DIAB100 MYOP"),
(4,"George","ACNE DIAB100"),
(5,"Alain","DIAB201");

LIKE

作用是在一个字符型字段列中检索包含对应子串的。LIKE 支持两种通配符,分别是'_'和'%'

  • '_'代表匹配1个任意字符,常用于充当占位符
  • '%'代表匹配0个或者多个任意字符

查conditions长度为7的数据

SELECT * FROM Patients WHERE conditions LIKE '_______';

查询以D开头的conditions数据

SELECT * FROM Patients WHERE conditions LIKE 'D%';

查询以P结尾的conditions数据

SELECT * FROM Patients WHERE conditions LIKE '%P';

以此查找包含前缀 DIAB1的onditions数据

SELECT patient_id,patient_name,conditions FROM Patients WHERE conditions LIKE '% DIAB1%' OR conditions LIKE 'DIAB1%';
  • 展示结果 image.png

三、执行结果

测试结果

image.png

四、总结

本题比较简单,主要是考察LIKE的使用,这里有两个细节,第一个是'% DIAB1%'前边要有空格,这个是查不在第一位的conditions数据,第二个是'DIAB1%'查找数据在第一位的数据。