简体   繁体   English

MySQL 组 Concat 在派生表上

[英]MySQL Group Concat on a derived table

So I have a derived table and I would like to do a GROUP_CONCAT() on the derived table while still getting all the columns of the derived table所以我有一个派生表,我想在派生表上执行GROUP_CONCAT() ,同时仍然获取派生表的所有列

For example, I have a table called patient and one called appointment, and I would like to get a GROUP_CONCAT() of appointment IDs per patient with given criteria.例如,我有一个名为患者的表和一个名为约会的表,我想为每个具有给定标准的患者获取一个约会 ID 的 GROUP_CONCAT()。

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

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

But the problem is that the GROUP_CONCAT() doesn't take any of the filters or anything else from the first derived table into consideration.但问题是 GROUP_CONCAT() 没有考虑任何过滤器或第一个派生表中的任何其他内容。 There can also be upwards of 20 million appointment records so I feel like the additional join is just doing unnecessary work...Any advice on how to work around this?也可能有超过 2000 万条约会记录,所以我觉得额外的加入只是在做不必要的工作......关于如何解决这个问题的任何建议? Thanks谢谢

I think the second subquery should be like this.我认为第二个子查询应该是这样的。 Because I think we don't need to join tables there.因为我认为我们不需要在那里加入表格。

    SELECT
      patient_id, 
      GROUP_CONCAT(appointment.appt_id) appointments,
    FROM
      appointment
    GROUP BY
      patient_id

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

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