2015-06-28 53 views
0

我有三張表,我想組合。我有一位醫生,耐心和操作。醫生代表所有的醫生。患者代表患者,手術持有患者和醫生的主要患者。 我如何寫一個查詢,它會顯示我chiefdoctor和assistantDocotor和Patient?到目前爲止,我到達了什麼?POSTGRES - 將同一列與不同文本組合在一行中

顯示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| 
+2

'%s /} /);/g ': - ] – wildplasser

+0

你是什麼意思由「%s /} /);/g: - ]」? : - ] –

+0

因此,您使用了一個'}'來終止表定義。並省略';' – wildplasser

回答

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) 

,但我得到了感覺這並不是你爲了保持解決方案更短而關注的主要問題,我把它留在了外面

+0

完美。我會在稍後嘗試修剪,因爲我整天坐在這上面。非常感謝你。 –

相關問題