使用Distinct进行联合选择

时间:2014-03-03 11:30:52

标签: sql distinct union

我有表存储我的答案和评论价值。我需要得到它,如果它是null或答案值然后结合。以下查询无效。它没有从表中获得任何价值。

SELECT DISTINCT 
       b.QM_ID,
       b.QM_QCM_ID,
       b.QM_Question,
       b.QM_Type,
       b.QM_Parent_Id,
       null,
       null 
  FROM question_master b 
       INNER JOIN Assessment_master d 
                  ON ((   d.AM_QM_ID = b.QM_Parent_Id 
                       OR d.AM_QM_ID = b.QM_ID) 
                      AND d.AM_HNM_ID = %d 
                      AND d.AM_HM_ID = %d 
                      AND d.AM_ASM_Local_Id = %@) 
 WHERE     b.QM_Parent_Id != 0 
       AND b.QM_Status = 'A' 
       AND b.QM_QCM_ID = %@ 
       AND b.QM_QRM_Id = %@ 
UNION 
SELECT DISTINCT 
       b.QM_ID,
       b.QM_QCM_ID,
       b.QM_Question,
       b.QM_Type,
       b.QM_Parent_Id,
       d.AM_Answer,
       d.AM_Comments 
  FROM question_master b 
       INNER JOIN Assessment_master d 
                  ON ((   d.AM_QM_ID = b.QM_Parent_Id 
                       OR d.AM_QM_ID = b.QM_ID) 
                      AND d.AM_HNM_ID = %d 
                      AND d.AM_HM_ID = %d 
                      AND d.AM_ASM_Local_Id = %@) 
 WHERE     b.QM_Parent_Id != 0 
       AND b.QM_Status = 'A' 
       AND b.QM_QCM_ID = %@ 
       AND b.QM_QRM_Id = %@

Question_Master:

QM_ID    QM_QRM_ID   QM_LCM_ID  QM_QCM_ID   QM_Question       QM_Parent_Id

432         5            19       1         question_parent       0
433         5            19       1         question_child        432
434         5            19       1           question_child1      432

Assessment_Master:

AM_ID     AM_UM_ID   AM_ASM_Local_Id  AM_QM_ID   AM_Answer   AM_Comments  AM_HNM_ID
1          8            1                433       NULL        testing      1

如果我回答孩子问题433,我只得到433孩子的父母。我没有得到434个问题。

a.QM_ID  a.QM_QCM_ID  a.QM_Question     a.QM_Parent_Id c.AM_Answer  c.AM_Comments
         432       1          question_parent     0                Null        NULL
          433      1          question_child       432             null        value

0 个答案:

没有答案