简体   繁体   English

是否可以从连接中的子查询结果中得到 select

[英]Is it possible to select from the result of a subquery in a join

So I have a large subquery and I would like to join on that subquery while using the result of the subquery in the join.所以我有一个很大的子查询,我想在连接中使用子查询的结果时加入该子查询。

For example, I have a table called patient and one called appointment , and I would like to get the number of appointments per patient with given criteria.例如,我有一张名为patient的表,还有一张名为appointment的表,我想根据给定的标准获取每位患者的预约次数。

Right now I am doing something like this:现在我正在做这样的事情:

SELECT
  t1.*
FROM
  (
    SELECT
      patient.name,
      patient.id,
      appointment.date
    FROM
      patient
      LEFT JOIN appointment ON appointment.patient_id = patient.id
    WHERE
      /* a **lot** of filters, additional joins, etc*/
  ) t1
  LEFT JOIN (
    SELECT
      COUNT(*) number_of_appointments,
      patient.id
    FROM
      patient
      LEFT JOIN appointment ON appointment.patient_id = patient.id
    GROUP BY
      patient.id
  ) t2 ON t1.id = t2.id

The problem is that this returns the number of appointments for each patient independent from the subquery above it.问题在于,这将返回每个患者的预约数量,与上面的子查询无关。 I tried writing the join as this:我试着这样写加入:

LEFT JOIN (
    SELECT
      COUNT(*) number_of_appointments,
      patient.id
    FROM
      t1
    GROUP BY
      patient.id
  )

But obviously I'm getting an error saying that table t1 doesn't exist.但显然我收到一个错误,说表 t1 不存在。 Is there any way for me to do this cleanly without having to repeat all of the filters from t1 in t2?有什么方法可以让我干净地做到这一点,而不必重复从 t1 到 t2 的所有过滤器?

Thanks!谢谢!

Why not use window functions?为什么不使用 window 函数?

SELECT p.name, p.id, a.date,
       COUNT(a.patient_id) OVER (PARTITION BY p.id) as num_appointments
FROM patient p LEFT JOIN
     appointment a
     ON a.patient_id = p.id
WHERE . . .

This provides the count based on the WHERE filtering.这提供了基于WHERE过滤的计数。 If you wanted a count of all appointments, then do the calculation before applying the WHERE :如果您想要计算所有约会,请在应用WHERE之前进行计算:

SELECT p.name, p.id, a.date,
       COALESCE(a.cnt, 0) as num_total_appointments,
       COUNT(a.patient_id) OVER (PARTITION BY p.id) as num_matching appointments
FROM patient p LEFT JOIN
     (SELECT a.*,
             COUNT(*) OVER (PARTITION BY a.patient_id) as cnt
      FROM appointment a
     ) a
     ON a.patient_id = p.id
WHERE . . .

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

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