我目前停留在sql查询上,试图找到一个解决方案,但现在让我头疼2次。我有3张桌子
用户表:
+-----+----------+-----------+
| pid | username | role |
+-----+----------+-----------+
| 1 | user1 | patient |
| 2 | user2 | patient |
| 3 | user3 | doc |
| 4 | user4 | assistant |
| 5 | user5 | patient |
+-----+----------+-----------+
基-DAT:
+-----+---------+-------+------------+
| pid | surname | name | birthdate |
+-----+---------+-------+------------+
| 1 | smith | john | 1950-07-31 |
| 2 | jackson | sarah | 1948-08-15 |
+-----+---------+-------+------------+
MED-DAT:
+-----+-----+---------------+--------+--------+
| mid | pid | dateLastEntry | weight | pulse |
+-----+-----+---------------+--------+--------+
| 1 | 1 | 2017-12-01 | 86 | 65 |
| 2 | 1 | 2017-12-02 | 84 | 70 |
| 3 | 1 | 2017-12-03 | 80 | 67 |
| 4 | 2 | 2017-11-15 | 66 | 60 |
| 5 | 2 | 2017-11-17 | 60 | 64 |
+-----+-----+---------------+--------+--------+
我试图为每个具有角色患者的用户获取max(dateLastEntry),显示他们的pid,姓名,姓氏,体重,脉冲在一行中 - 即使没有医疗数据条目病人:这样的事情:
+-----+---------+-------+------------+--------+-------+
| pid | surname | name | lastEntry | weight | pulse |
+-----+---------+-------+------------+--------+-------+
| 1 | smith | john | 2017-12-02 | 84 | 70 |
| 2 | jackson | sarah | 2017-11-17 | 60 | 64 |
| 5 | NONE | NONE | NONE | NONE | NONE |
+-----+---------+-------+------------+--------+-------+
Atm我的陈述看起来像这样,但无法得到正确的结果:
select b.pid, s.surname, s.name, max(m.date) as lastEntry, m.weight, m.pulse
from users b
left join med-dat m on b.pid = m.pid
left join base-dat s on m.pid = s.pid
where b.role = 'Patient'
group by b.pid, s.surname, s.name, m.weight;
答案 0 :(得分:0)
您可以按如下所示重写查询以获得所需的输出
select b.pid, s.surname, s.name, m.dateLastEntry as lastEntry, m.weight, m.pulse
from users b
left join med_dat m on b.pid = m.pid
left join base_dat s on m.pid = s.pid
left join med_dat m1 on m.pid = m1.pid
and m.dateLastEntry < m1.dateLastEntry
where m1.pid is null
and b.role = 'Patient'
根据评论进行修改,使用用户表格中的pid加入base_dat
select b.pid, s.surname, s.name, m.dateLastEntry as lastEntry, m.weight, m.pulse
from users b
left join med_dat m on b.pid = m.pid
left join base_dat s on b.pid = s.pid
left join med_dat m1 on m.pid = m1.pid and m.dateLastEntry < m1.dateLastEntry
where m1.pid is null
and b.role = 'Patient'
group by b.pid, s.surname, s.name, m.weight;