POSTGRES - 将相同的列与一行中的不同文本组合在一起

时间:2015-06-28 19:03:40

标签: sql database postgresql

我想要组合三个表。我有一名医生,病人和手术。医生代表医生的一切。患者代表患者并且手术持有患者和医生的主要医生。 我如何写一个查询,它将显示我的ChiefDoctor和assistantDocotor和病人?到目前为止我到底做了什么?

显示Chiefdoctor或Assistantdoctor的名字和姓氏。我如何写一个包含Chief和Assistant的表?

select a.vorname|| ' ' || a.nachname AS leitenderArzt, p.firstname || ' ' || p.lastname AS patient
from angestellter a inner join operation o on a.id = o.leitenderarzt
inner join patient p on o.patientident=p.ident

| id | firstname       | lastname      | patient      |
| 1  | ImA             | ChiefDoctor1  | p.firstname  |
| 3  | ImA             | ChiefDoctor3  | p.firstname  |

我的数据库的基础结构,带有表示。

CREATE TABLE doctor
(
  id serial NOT NULL,  
  firstname character varying(255) NOT NULL,
  lastname character varying(255) NOT NULL,  
  CONSTRAINT angestellter_pkey PRIMARY KEY (id),
}

 Table doctor
 |id | firstname | lastname        |
 | 1 | ImA       | ChiefDoctor1    |
 | 2 | ImA       | AssistantDoctor |
 | 3 | ImA       | ChiefDoctor2    |

CREATE TABLE patient
(
  ident serial NOT NULL,  
  firstname character varying(255) NOT NULL,
  lastname character varying(255) NOT NULL,
  CONSTRAINT patient_pkey PRIMARY KEY (ident),
}

Table patient
| ident | firstname | lastname |
| 1     | Operated  | ME       |

CREATE TABLE operation
(
  id serial NOT NULL,
  chiefDoctor integer NOT NULL,
  AssistantDoctor integer NOT NULL,
  patientident integer NOT NULL,
  CONSTRAINT operation_pkey PRIMARY KEY (id),
  CONSTRAINT fkoperation539608 FOREIGN KEY (patientident)
      REFERENCES patient (ident) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkoperation745809 FOREIGN KEY (assistantDoctor)
      REFERENCES angestellter (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkoperation949671 FOREIGN KEY (chiefDoctor)
      REFERENCES angestellter (id) MATCH SIMPLE
}

Table operation
| id | doctorID | doctorID | patientID |
| 1  |    1     |    2     |     1     |

如何编写一个查询,显示谁操作了全名患者?它看起来应该是这样的。

| id | chiefdoctor       | assistantdoctor      | patient      |
|----| ImA + ChiefDoctor |ImA + AssistantDoctor | Operated + ME|

1 个答案:

答案 0 :(得分:3)

第一种也许是最直观的方法是两次加入医生:

select o.id
     , d1.firstname || ' + ' || d1.lastname as chiefdoctor
     , d2.firstname || ' + ' || d2.lastname as assistantdoctor
     , p.firstname || ' + ' || p.lastname as patient
from operation o
join doctor d1
    on o.chiefDoctor = d1.id
join doctor d2
    on o.AssistantDoctor = d2.id
join patient p
    on o.patientident = p.ident

您可能希望修剪名称,如下所示:

trim(both from d1.firstname) || ' + ' || trim(both from d1.lastname)

但我觉得这不是你所关注的主要问题,所以为了让解决方案更短,我把它留了出来