简体   繁体   中英

Query using CASE, WHEN, THEN in postgresql not working

I have three tables, tbl_doctors_details , tbl_time and tbl_token .

I have to select the details from tbl_time or tbl_token . That is if for particular doctor in hospital have t_type is time then select from tbl_time else select from tbl_token .

For example, for doctor_id is 100 and hospital_id 1, the t_type is time . So for this user, details should select from tbl_time table.

Below is the sample structure and data of three tables:

在此处输入图片说明 在此处输入图片说明

How can I use CASE condition in query here?

I tried:

SELECT *
FROM 
( SELECT * CASE WHEN t_type= 'time'  FROM dbname.tbl_doctors_details t1 THEN
           dbname.tbl_time t2
           ELSE
           dbname.tbl_token t2
           WHERE t1.hospital_id=t2.hospital_id AND t1.doctor_id=t2.doctor_id);

I know the query is not working, but how can I make the query working?

You need to join both tables using two LEFT JOINs and then COALESCE to find the matching data:

SELECT t1.*,
   colaesce(t_time.hospid, t_token.hospid),
   colaesce(t_time.start, t_token.start)
FROM dbname.tbl_doctors_details t1
LEFT JOIN dbname.tbl_time t_time
  ON t1.doctor_id=t_time.doctor_id
 AND t1.t_type= 'time'
LEFT JOIN dbname.tbl_token t_token
  ON t1.doctor_id=t_token.doctor_id
 AND t1.t_type= 'token';

Use CASE WHEN in your SELECT and LEFT JOIN both tables. In both LEFT JOIN use the condition of t_type to join on the tables. In your SELECT you can now check whether table t1 or t2 was joined and select the preferred column. Here's a sample (the selected column is just a sample to illustrate):

SELECT CASE WHEN t1.id IS NULL THEN t2.id ELSE t1.id END AS joined_id
FROM tbl_doctors_details as tbl_base
LEFT JOIN tbl_time t1 ON t1.t_type = 'time' AND t1.doc_id = tbl_base.doc_id
LEFT JOIN tbl_token t2 ON t2.t_type = 'token' AND t2.doc_id = tbl_base.doc_id

Serious smell of doing homework for someone here.. Meh

SELECT

  doctors.*
  , CASE
    WHEN doctors.type = 'time' THEN time.start
    ELSE token.start
  END AS start

FROM

doctors

  LEFT OUTER JOIN time
    ON time.doc_id = doctors.doc_id
    AND time.hospital_id = doctors.hospital_id
    AND doctors.t_type = 'time'

  LEFT OUTER JOIN token
    ON token.doc_id = doctors.doc_id
    AND token.hospital_id = doctors.hospital_id
    AND doctors.t_type = 'token'

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