MySQL Query中的条件表更改

时间:2012-08-29 21:24:44

标签: mysql sql conditional

我试图解决这个问题。但我认为我没有在哪里。

我有3张桌子:

此故事包含所有问题和问题类型:

    Table: Ref
    id    |    type   |   info
    ==========================
    1          SS         Education
    ---------------------------
    2          RB         Gender
    ---------------------------
    3          ST         State

此表包含上表'Ref`

中问题的“选项”
    Table: ref_ans
    id    |  q_id   |   answer_text
    ===========================
    1          1        Masters     
    ---------------------------
    2          1        Bachelors     
    ---------------------------
    3          1        Undergrad
    ---------------------------
    4          2        Male     
    ---------------------------
    5          2        Female
    ---------------------------
    6          2        Dont want to disclose

此表包含状态(表type中的Ref =“ST”)

    Table: us_states

    id    |  answer_text 
    ===========================
    1        Alaska     
    ---------------------------
    2        Alabama     
    ---------------------------
    3        Arkansan
    ---------------------------
    4        Arizona     
    ---------------------------
    5        Baltimore
    ---------------------------
    etc

我想要的结果是:

    ref.id, ref_ans.id, ref.answer_text / us_states.answer_text
对于给定的ref.question_id * ,

*

条件是:如果question_id,请求的答案是'ST',它应该从us_states拉出答案,否则,它应该从ref-ans表中拉出来。

我试过这个。显然,这不起作用:

    SELECT ref.id, 
         CASE WHEN ref.type = 'ST' THEN 
             (SELECT ID, answer_text FROM us_states )
         ELSE 
             (SELECT id, answer_text FROM ref_ans)  
    END

    FROM ref
   WHERE ref.ID = <id>

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试:

SELECT    a.id, 
          COALESCE(b.id, c.id) AS ans_id,
          COALESCE(b.answer_text, c.answer_text) AS answer_text
FROM      ref a
LEFT JOIN ref_ans b ON a.id = b.q_id
LEFT JOIN us_states c ON a.type = 'ST'
WHERE     a.id = <id> AND (
              (a.type <> 'ST' AND b.id IS NOT NULL) OR
              (a.type =  'ST' AND c.id IS NOT NULL)
          )

答案 1 :(得分:0)

假设所有三个表都通过id(第1列)连接:

  SELECT ref_ans.id, ref.id, if(ref.type='ST', us_states.answer_text, ref_ans.answer_text) as answer_text
    FROM ref_ans  
    JOIN ref  on ref.id=ref_ans.id
    JOIN us_states on ref.id=us_states.id
    WHERE ref_ans.q_id = <id>