简体   繁体   English

MYSQL 子查询结果列不符合预期

[英]MYSQL subquery results columns not as expected

I am trying to build a query that will build a output like this.我正在尝试构建一个查询来构建这样的输出。

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

The output that I go is this我去的输出是这个

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

I was following the instructions here https://www.mysqltutorial.org/mysql-subquery/我按照这里的说明https://www.mysqltutorial.org/mysql-subquery/

My query is this我的查询是这样的

 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 );

What I was expecting to happen was the alias 'patient appt' to be populated with the data from the nested select statement.我期望发生的是别名“患者应用程序”将填充来自嵌套选择语句的数据。 I was thinking this would work because I am trying to produce multiple columns that are going to be populated by subqueries.我认为这会起作用,因为我正在尝试生成将由子查询填充的多个列。 All of the columns are counts of appointments in the calendar table.所有列都是日历表中的约会计数。

So, does the 'patient appt' need to be a column in the patient_data table?那么,“患者应用程序”是否需要成为患者数据表中的一列? If so, is there another way to produce the desired column data?如果是这样,是否有另一种方法来生成所需的列数据?

Put the correlated subquery directly in the select clause:将相关子查询直接放在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'

Note: don't use single quotes for column aliases!注意:不要对列别名使用单引号! They are meant for literal strings only.它们仅用于文字字符串。 In MySQL, you can use backticks to quote identifiers - but better yet, use identifiers that do not require quoting, so you don't have to worry about that.在 MySQL 中,您可以使用反引号来引用标识符 - 但更好的是,使用不需要引用的标识符,因此您不必担心。

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

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