-2

我对 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. 对于 (1) 中找到的每个问题行,找到所有答案行,其中answer.questionId=question.id
  3. 对于 (2) 中找到的每个答案,找到vote.answerId=的所有投票行answer.id
  4. 返回每个唯一 answerId 的投票行数。

因此,如果我有以下测试数据:

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 查询来执行?

4

2 回答 2

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

请注意,您不能创建这样一组测试数据。因为表中 answerId 的值vote违反了该表中的外键约束answerId22表中不存在answer

于 2013-10-18T01:21:31.353 回答
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

Is what I think you are looking for.

于 2013-10-17T23:33:44.687 回答