SQL查询加入3个表

时间:2013-10-17 22:23:28

标签: sql postgresql

我对SQL很新,所以我不确定我要做的事情是否被称为连接。

我有4个表,使用此架构:

CREATE TABLE survey (
    id           serial    PRIMARY KEY,
    title        text,
    password     text
);

CREATE TABLE question (
    id           serial    PRIMARY KEY,
    surveyId     integer   REFERENCES survey(id),
    value        text
);

CREATE TABLE answer (
    id           serial    PRIMARY KEY,
    questionId   integer   REFERENCES question(id) ,
    value text
);

CREATE TABLE vote (
    id           serial,
    questionId   integer   REFERENCES question(id),
    answerId     integer   REFERENCES answer(id)
);

鉴于具体的survey.id(surveyId),我需要:

  1. 查找question.surveyId = surveyId
  2. 的所有问题行
  3. 对于(1)中找到的每个问题行,找到answer.questionId = question.id
  4. 的所有答案行
  5. 对于(2)中找到的每个答案,找到vote.answerId = answer.id的所有投票行。
  6. 返回每个唯一answerId的投票行数。
  7. 所以,如果我有以下测试数据:

    question
    =============
    id | surveyId
    1  | 3
    2  | 3
    3  | 3
    4  | 5
    5  | 6
    
    
    answer
    ===============
    id | questionId
    1  | 1
    2  | 1
    3  | 2
    4  | 3
    
    
    vote
    ==========================
    id | questionId | answerId
    1  | 1          | 1
    2  | 1          | 2
    3  | 1          | 1
    4  | 2          | 3
    5  | 4          | 22
    

    如果初始surveyId为3,那么我希望此查询的结果为:

    answerId | count
    ================
    1        | 2
    2        | 1
    3        | 1
    

    有没有办法以单个SQL查询的方式执行此操作?

2 个答案:

答案 0 :(得分:1)

以下是您需要的查询:

SELECT v.answerId, COUNT(*) 
FROM survey AS s 
     INNER JOIN question AS q ON s.id = q.surveyId
     INNER JOIN answer AS a ON q.id = a.questionId
     INNER JOIN vote AS v ON a.id = v.answerId
WHERE  s.id = 3 -- This's your specific value of surveyId
GROUP BY v.answerId 
ORDER BY v.answerId

但可以优化此查询。根据表的关系,您可以放弃单个连接:

SELECT v.answerId, COUNT(*) 
FROM survey AS s 
     INNER JOIN question AS q ON s.id = q.surveyId AND s.id = 3
     INNER JOIN vote AS v ON q.id = v.questionId
GROUP BY v.answerId 
ORDER BY v.answerId

请注意,您无法创建这样的测试数据集。因为表vote中的answerId值违反了此表中的外键约束answerId。表22中没有answer

答案 1 :(得分:0)

SELECT 
  a.answerId
  , vote = COUNT(v.vote) 
FROM survey s
  INNER JOIN question q
    ON s.surveyid = q.surveyId
  INNER JOIN answer a
    ON q.questionId = a.questionID
  INNER JOIN vote v
    ON a.answerId = v.answerId
WHERE s.surveyID = @yourValue
GROUP BY a.answerId

我认为你在寻找什么。