在postgresql中使用CASE,WHEN,THEN查询不起作用

时间:2016-09-26 05:54:15

标签: sql postgresql case

我有三个表,tbl_doctors_detailstbl_timetbl_token

我必须从tbl_timetbl_token中选择详细信息。也就是说,如果医院中的特定医生t_typetime,则从tbl_time中选择,然后选择tbl_token

例如,doctor_id为100且hospital_id为1,t_typetime。因此,对于此用户,详细信息应从tbl_time表中选择。

以下是三个表的样本结构和数据:

enter image description here enter image description here

如何在查询中使用 CASE 条件?

我试过了:

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

我知道查询无效,但如何使查询正常工作?

3 个答案:

答案 0 :(得分:0)

您需要使用两个LEFT JOIN连接两个表,然后使用COALESCE来查找匹配数据:

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

答案 1 :(得分:0)

CASE WHENSELECT两个表中使用LEFT JOIN。在LEFT JOIN中,使用t_type的条件加入表。在SELECT中,您现在可以检查表t1t2是否已加入,并选择首选列。这是一个示例(所选列只是一个示例):

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

答案 2 :(得分:0)

在这里为某人做家庭作业的气味很明显...... 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'