-1

我有两张表用于多项选择问卷(每个用户回答一系列问题):

users (userID, name, email)

votes (voteID, userID, questionID, answerID)

样本数据(用户):

0, Some Name, some@thing.com
1, Other Name, some@one.com

样本数据(票数):

0, 1, 1, 1
1, 1, 2, 2
2, 1, 3, 2

我想选择所有有正确答案的用户。

我试过这个(我已经硬编码了答案):

$sql = "SELECT users.userID, users.name, users.email FROM users
INNER JOIN votes ON (users.userID = votes.userID)
WHERE (votes.questionID = '1' AND votes.answerID = '1')
AND (votes.questionID = '2' AND votes.answerID = '2')
AND (votes.questionID = '3' AND votes.answerID = '2')
AND (votes.questionID = '4' AND votes.answerID = '3')
AND (votes.questionID = '5' AND votes.answerID = '1')
GROUP BY users.userID";

但这不会返回任何东西。

我也尝试过这样的事情(我也硬编码了答案):

$sql = "SELECT users.userID, users.name, users.email FROM users
INNER JOIN transfertipsvotes ON (users.userID = transfertipsvotes.userID)
WHERE (transfertipsvotes.questionID = '1' AND transfertipsvotes.answerID = '1') GROUP BY users.userID
UNION
SELECT users.userID, users.name, users.email FROM users
INNER JOIN transfertipsvotes ON (users.userID = transfertipsvotes.userID)
WHERE (transfertipsvotes.questionID = '2' AND transfertipsvotes.answerID = '2') GROUP BY users.userID
UNION
SELECT users.userID, users.name, users.email FROM users
INNER JOIN transfertipsvotes ON (users.userID = transfertipsvotes.userID)
WHERE (transfertipsvotes.questionID = '3' AND transfertipsvotes.answerID = '2') GROUP BY users.userID";

但这只会为所有用户返回一个正确答案。

如何进行正确的查询以选择所有具有正确答案的用户?

4

2 回答 2

0

如果我对您的理解正确,您希望回答所有问题的用户都正确。在这种情况下,您应该使用 INTERSECT 而不是 UNION

但是为此,您的问题与您的问题一样多次。最好在 where "((question1 and Answer1) or (question2 and Answer2))" 中使用 OR 子句。最后根据用户 ID 做一个组并获取正确答案的计数,并仅获取那些所有正确答案的成员。

于 2013-08-27T11:16:41.607 回答
0

As far as I can see it now you need to use an INNER JOIN for each question, so each inner join will look like this:

INNER JOIN votes AS q1 ON (users.userID = q1.userID) AND q1.questionID = '1' AND q1.answerID ='1'

Repeat this for each question and you can check it.

于 2013-08-27T11:16:10.480 回答