如何在不使用辅助表的情况下连接两个只应该在查询中的表? (使用两列的左连接可以工作)

时间:2013-12-27 15:02:43

标签: mysql sql

我必须处理一个不完美的模型,因为两个不同的表应该只有一个......让我们简化模型并展示它:

Table: Survey
Columns: ID_SURVEY | SURVEY_TYPE | SURVEY_QUESTIONS

Table: SurveySent
Columns: ID_SENT | ID_USER | ID_SURVEY | TMST_SENT

Table: SurveyAnswered
Columns: ID_RECEIVED | ID_USER | ID_SURVEY | TMST_RECEIVED | ANSWERS

-- the first column is the primary key, columns wiht same name are foreign keys

现在,如果我建立了模型SurveyAnswered和SurveySent将是同一个表,因为只有在首次发送调查时才会回答调查,或者至少根据发送的调查进行调查回答。

然而情况并非如此,所以我试图用一个查询得到结果,希望有效,因为我不能写任何东西。

我想要得到的是用户收到的调查数量,该用户已经回答的调查数量,以及针对一种特定类型调查的调查数量。经过多次尝试,我设法做到这一点的唯一方法是加入两个子查询:

SELECT Z.ID_USER, COUNT(DISTINCT ID_SENT), COUNT(DISTINCT ID_RECEIVED) FROM
  (SELECT A1.ID_USER, A1.ID_SENT 
    FROM SurveySent A1 
    JOIN Survey B ON A1.ID_SURVEY = B.ID_SURVEY 
   WHERE B.SURVEY_TYPE = @MyType) AS Z
LEFT JOIN
   (SELECT A2.ID_USER, A2.ID_RECEIVED 
    FROM SurveyAnswered A2 
    JOIN Survey B ON A2.ID_SURVEY = B.ID_SURVEY 
   WHERE B.SURVEY_TYPE = @MyType) AS Y
ON Z.ID_USER = Y.ID_USER
GROUP BY Z.ID_USER

有没有办法用一个查询(不是一个有2个子查询)执行此操作?似乎问题的核心是我想同时加入两个列:ID_SURVEY和ID_USER但我还没有找到一种方法在单个查询中执行此操作...

类似的事情:

SELECT A1.ID_USER, COUNT(DISTINCT ID_SENT), COUNT(DISTINCT ID_RECEIVED)
FROM SurveySent A1
LEFT JOIN SurveyAnswered A2 ON A1.ID_USER=A2.ID_USER
JOIN Survey B ON B.ID_SURVEy = A1.ID_SURVEY
WHERE B.SURVEY_TYPE = @MyType
 AND (A2.ID_SURVEY = B.ID_SURVEY OR A2 IS NULL)
GROUP BY A1.ID_USER

不能正常工作,因为在左连接之后空值丢失了......任何帮助?

1 个答案:

答案 0 :(得分:0)

使用survey表来“驱动”查询。也就是说,将它作为第一个表并使用left outer join s。

SELECT s.ID_USER, COUNT(DISTINCT ss.ID_SENT), COUNT(DISTINCT sa.ID_RECEIVED)
FROM Survey s left outer join
     SurveySent ss
     on s.id_survey = ss.id_survey left outer join
     SurveyAnswered sa
     on s.id_survey = sa.id_survey and ss.id_user = sa.id_user
WHERE B.SURVEY_TYPE = @MyType;