0

我试图解决这个问题。但我想我无处可去。

我有 3 张桌子:

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

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

此表包含上表“参考”中问题的“选项”

    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的 =“ST” Ref

    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>

有任何想法吗?

4

2 回答 2

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)
          )
于 2012-08-29T21:32:11.040 回答
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>
于 2012-08-29T22:11:35.553 回答