我是新来的,有人可以解决我无法用子查询解决的问题,任何想法如何解决问题?
基本上我需要所有患者" pa_name",每个"字段的最新检查:pe_d2"喜欢"预期结果:"
我试图勾勒出结果,可能有助于理解问题......
" pacient_exams"表有很多记录,查询需要非常快。
提前感谢您寻求可能的解决方案! []
patient_exams
+-------+----------+----------+------------+------------+
| pe_id | pe_pa_id | pe_ex_id | pe_d1 | pe_d2 |
+-------+----------+----------+------------+------------+
| 1 | 1 | 1 | 2014-05-19 | 2016-05-19 |
| 2 | 1 | 2 | 2014-05-19 | 2015-05-19 |
| 3 | 1 | 3 | 2014-05-26 | 2014-11-26 |
| 4 | 1 | 3 | 2014-05-19 | 2014-11-19 |
| 5 | 1 | 4 | 2013-05-19 | 2013-11-19 |
| 6 | 1 | 4 | 2014-05-19 | 2014-11-19 |
| 7 | 3 | 1 | 2013-08-19 | 2014-08-19 |
| 8 | 3 | 1 | 2014-05-01 | 2017-05-01 |
| 9 | 4 | 2 | 2013-05-02 | 2014-05-02 |
| 10 | 4 | 2 | 2013-11-01 | 2014-05-01 |
| 11 | 4 | 4 | 2013-05-02 | 2014-05-02 |
| 12 | 4 | 4 | 2013-11-01 | 2014-05-01 |
+-------+----------+----------+------------+------------+
patient exams
+-------+---------+ +-------+---------+
| pa_id | pa_name | | ex_id | ex_name |
+-------+---------+ +-------+---------+
| 1 | John M. | | 1 | Exam 1 |
| 2 | Slater | | 2 | Exam 2 |
| 3 | Jonny | | 3 | Exam 3 |
| 4 | Jessy | | 4 | Exam 4 |
| ... | ... | | ... | ... |
+-------+---------+ +-------+---------+
预期结果:
+-------+---------+---------+------------+------------+
| pe_id | pa_name | ex_name | pe_d1 | pe_d2 |
+-------+---------+---------+------------+------------+
| 9 | Jessy | Exam 2 | 2013-05-02 | 2014-05-02 |
| 11 | Jessy | Exam 4 | 2013-05-02 | 2014-05-02 |
| 1 | John M. | Exam 1 | 2014-05-19 | 2016-05-19 |
| 2 | John M. | Exam 2 | 2014-05-19 | 2015-05-19 |
| 3 | John M. | Exam 3 | 2014-05-26 | 2014-11-26 |
| 6 | John M. | Exam 4 | 2014-05-26 | 2014-11-26 |
| 8 | Jonny | Exam 1 | 2014-05-01 | 2017-05-01 |
+-------+---------+---------+------------+------------+
答案 0 :(得分:0)
您可以在表格中使用联接,对于最长考试日期,您需要使用子查询进行patient_exams
的额外自我加入,以获得考试日期的最大值,即max(pe_d2)
select
pe.pe_id,
p.pa_name ,
e.ex_name ,
pe.pe_d1 ,
pe.pe_d2
from exams e
join patient_exams pe on(e.ex_id = pe.pe_ex_id)
join patient p on(p.pa_id= pe.pe_pa_id)
join (select `pe_pa_id`, `pe_ex_id` ,max(pe_d2) pe_d2
from patient_exams
group by `pe_pa_id`, `pe_ex_id`) pee
on (pe.`pe_pa_id`= pee.`pe_pa_id` and
pe.`pe_ex_id` = pee.`pe_ex_id` and
pe.pe_d2 = pee.pe_d2
)
order by p.pa_name ,pee.pe_d2 desc
答案 1 :(得分:0)
您需要先从patient_exams表中获取最新记录,然后将所有3个表与过滤后的结果一起加入,如下所示:
SELECT pe_id, pa_name, ex_name, pe_d1, pe_d2
FROM patient_exams pe
JOIN patient p
ON pe.pe_pa_id = p.pa_id
JOIN exams e
ON pe.pe_ex_id = e.ex_id
JOIN (
SELECT pe_pa_id, pe_ex_id, MAX(pe_d2) AS max_pe_d2
FROM patient_exams
GROUP BY pe_pa_id, pe_ex_id
) AS t
ON pe.pe_pa_id = t.pe_pa_id
AND pe.pe_ex_id = t.pe_ex_id
AND pe.pe_d2 = t.max_pe_d2
ORDER BY pa_name, ex_name
感谢大家,工作正常!