Leetcode-SQL学习计划-SQL入门-1527.患某种疾病的患者【regexp正则表达式匹配】

2023-02-12,,,,

链接:https://leetcode.cn/problems/patients-with-a-condition/

-- 1527.患某种疾病的患者
-- 链接:https://leetcode.cn/problems/patients-with-a-condition/
-- 写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1 。
CREATE TABLE IF NOT EXISTS Patients (patient_id INT, patient_name VARCHAR(30), conditions VARCHAR(100));
TRUNCATE TABLE Patients;
INSERT INTO Patients (patient_id, patient_name, conditions) VALUES ('1', 'Daniel', 'YFEV COUGH');
INSERT INTO Patients (patient_id, patient_name, conditions) VALUES ('2', 'Alice', '');
INSERT INTO Patients (patient_id, patient_name, conditions) VALUES ('3', 'Bob', 'DIAB100 MYOP');
INSERT INTO Patients (patient_id, patient_name, conditions) VALUES ('4', 'George', 'ACNE DIAB100');
INSERT INTO Patients (patient_id, patient_name, conditions) VALUES ('5', 'Alain', 'DIAB201'); -- 查询所有数据
SELECT * FROM Patients; -- 查询以DIAB1开头的患者
-- 方式1:使用LIKE
SELECT * FROM Patients
WHERE
conditions LIKE 'DIAB1%'
OR
conditions LIKE '% DIAB1%';
-- 方式2:使用正则表达式匹配
-- 正则表达式(regular expression)【REG EXP】
SELECT * FROM Patients
WHERE conditions REGEXP '\\bDIAB1'
-- 第一个\表示转义字符 -- \s是指空白,包括空格、换行、Tab 缩进等所有的空白
-- 即\\s -- \b,单词边界符能够匹配中文符号、英文符号、空格、制表符、回车符号,以及各种边界,比如单词在开头,单词在结尾。 SELECT * FROM Patients
WHERE conditions REGEXP '^DIAB1| +DIAB1'

Leetcode-SQL学习计划-SQL入门-1527.患某种疾病的患者【regexp正则表达式匹配】的相关教程结束。

《Leetcode-SQL学习计划-SQL入门-1527.患某种疾病的患者【regexp正则表达式匹配】.doc》

下载本文的Word格式文档,以方便收藏与打印。