简体   繁体   English

在MYSQL的多个表中选择MAX

[英]Select MAX among multiple tables in MYSQL

I am trying to list patients and their most recent primary insurance benefits. 我正在尝试列出患者及其最近的主要保险利益。 I have three tables involved, 我涉及三个表,

patients (contains patient demographic data) 患者(包含患者人口统计数据)
benefits (contains insurance benefits information) 福利(包含保险利益信息)
rel_pat_ben (matches primary keys of patient table with corresponding key on benefits table) rel_pat_ben(将患者表的主键与福利表上的对应键进行匹配)

I almost solved the problem with this: 我几乎解决了这个问题:

SELECT p.patient_id, MAX(b.benefits_id), b.effective_date 选择p.patient_id,MAX(b.benefits_id),b。生效日期
FROM patients AS p 来自患者AS p
LEFT JOIN rel_pat_ben AS rpb USING(patient_id) 左联接rel_pat_ben AS rpb使用(患者ID)
LEFT JOIN benefits AS b ON (rpb.benefits_id=b.benfits_id AND b.order='primary') 左加入将使b受益(rpb.benefits_id = b.benfits_id AND b.order ='primary')
GROUP BY patient_id GROUP BY Patient_id

Using MAX seemed to work as the id field is auto-incremented, but I realized my problem when I found cases where a record that has a lower id was edited with newer information. 由于id字段是自动递增的,因此使用MAX似乎可以工作,但是当我发现用新信息编辑具有较低id的记录时,我意识到了我的问题。 So really, I need to check the 'effective_date' field. 所以说真的,我需要检查“有效日期”字段。

Is there a way to return just one record per patient that contains only the most recent insurance benefits? 有没有一种方法可以使每位患者仅返回一份仅包含最新保险利益的记录?

What if you try adding 如果您尝试添加

ORDER BY b.effective_date DESC

after the GROUP BY clause? 在GROUP BY子句之后?

This will select the maximum effective_date, if it exists, for every patient: 这将为每个患者选择最大有效日期(如果存在):

SELECT p.patient_id, MAX(b.effective_date)
FROM
  patients AS p INNER JOIN rel_pat_ben AS rpb USING(patient_id)
  INNER JOIN benefits AS b ON (rpb.benefits_id=b.benfits_id AND b.order='primary')
GROUP BY
  p.patient_id

and this will select last benefit for every patient: 这将为每个患者选择最后的好处:

SELECT p.patient_id, b.*
FROM
  patients AS p INNER JOIN rel_pat_ben AS rpb USING(patient_id)
  INNER JOIN benefits AS b ON (rpb.benefits_id=b.benfits_id AND b.order='primary')
WHERE
  (p.patient_id, b.effective_date) IN (
    SELECT p.patient_id, MAX(b.effective_date)
    FROM
      patients AS p INNER JOIN rel_pat_ben AS rpb USING(patient_id)
      INNER JOIN benefits AS b ON (rpb.benefits_id=b.benfits_id AND b.order='primary')
    GROUP BY
      p.patient_id
  )

I'm using INNER JOINS so if there are no benefits for a patient, it won't be returned. 我使用的是INNER JOINS,因此,如果对患者没有好处,则不会退还。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM