【问题标题】:MYSQL subquery results columns not as expectedMYSQL 子查询结果列与预期不符
【发布时间】:2021-02-19 12:14:37
【问题描述】:

我正在尝试构建一个查询来构建这样的输出。

 +-----------------+--------------+
 | Name            | patient appt |
 +-----------------+--------------+
 | Dharmick Ketan  |           75 |
 | See Ka Wai      |           45 |
 | Totoritis Susan |           25 |
 | Seay Duval      |          147 |
 +-----------------+--------------+

我去的输出是这样的

 +-----------------+--------------+
 | Name            | patient appt |
 +-----------------+--------------+
 | Dharmick Ketan  | patient appt |
 | See Ka Wai      | patient appt |
 | Totoritis Susan | patient appt |
 | Seay Duval      | patient appt |
 +-----------------+--------------+

我按照这里的说明进行操作 https://www.mysqltutorial.org/mysql-subquery/

我的查询是这样的

 mysql> select concat(p.lname,' ' , p.fname) as 'Name',
->                         'patient appt'   
->                         from patient_data as p
->                         where
->                          p.financial_review_exp>'2019-07-01'
->                         and
->                         'patient appt' = ( select count(*) from openemr_postcalendar_events e
->                         where e.pc_pid = p.pid );

我期望发生的是别名“患者 appt”将填充嵌套选择语句中的数据。我认为这会起作用,因为我正在尝试生成将由子查询填充的多个列。所有列都是日历表中的约会计数。

那么,“患者应用程序”是否需要成为患者数据表中的一列?如果是这样,是否有另一种方法来生成所需的列数据?

【问题讨论】:

    标签: mysql sql count subquery where-clause


    【解决方案1】:

    将相关子查询直接放在select子句中:

    select concat(p.lname,' ' , p.fname) as name,
        (select count(*) from openemr_postcalendar_events as e where e.pc_pid = p.pid) as patient_appt
    from patient_data as p
    where p.financial_review_exp > '2019-07-01'
    

    注意:不要对列别名使用单引号!它们仅适用于文字字符串。在 MySQL 中,您可以使用反引号来引用标识符 - 但更好的是,使用不需要引用的标识符,因此您不必担心这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多