简体   繁体   中英

How to add relationship to table rows based on column value in psql?

I have a table of patients and a table of doctors . I would like to assign a doctor to every patient . Doctors may have many patients but a Patient will belong to a single Doctor. I would like to assign a specific doctor based on the born_on value of the patient .

Currently I am using a SET and WHERE clause to assign patients with a born_on below 10 to the doctor with an id of 1 .

 UPDATE patients p
  SET doctor_id = d.id
  FROM doctors d
  WHERE DATE_PART('year', AGE(p.born_on)) < 10
  AND d.id = 1;

How could I, in minimal number of queries, assign all patients to a doctor based on their born_on attribute.

The conditions are below

age - d.id
< 10 is 1
< 20 is 2
< 30 is 3
< 40 is 4
< 50 is 5
< 60 is 6
< 70 is 7
< 80 is 8
< 90 is 9
>= 100 is 10

I was wondering, if you already know the condition for update, do you have to go to the Doctor's table (meaning something like below)

UPDATE patients p
  SET doctor_id = case DATE_PART('year', AGE(p.born_on)) 
                  when < 10 then 1
                  when < 20 then 2 
                  ...
                  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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