1527. 患某种疾病的患者

Leetcode题目:正则表达式

患者信息表: 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 开头的疾病。

解题思路

正则表达式

国庆假期不是很想做题啊…早上写的动态规划题实在没心思做,还是来道简单的SQL题调节调节心情吧。

DIAB1开头的话,从题目来看有两种情况

  • DIAB1xxx xxxxx
  • xxxx DIAB1xxxx

也不难理解。那只有看一个前面不带空格,一个带空格,其他全部无视就好了。上午在看其他题的题解的时候看到了正则表达式的用法。自己百度学了下,嘛,大致用法如下

# Write your MySQL query statement below
SELECT * FROM Patients
WHERE conditions REGEXP ' DIAB1|^DIAB1'

貌似还能更简洁,不过这个能看懂就行了。^表示开头是否包含xxx。不过正则表达式能用或就很不错,省的写condition … OR condition ….了。

Subscribe
提醒
0 评论
Inline Feedbacks
View all comments
0
在此留下你的评论x