[英]Sql query which returns multiple rows matching criteria
I have a survey system which the following questionanswer
table 我有一个调查系统,下面的
questionanswer
表
questionId personId response
1 a red
2 a blue
3 a green
4 a black
1 b red
2 b blue
3 b green
4 b black
I need to construct a query for a search form allowing users to pick the question and the response to be returned. 我需要为搜索表单构造一个查询,以允许用户选择问题和要返回的响应。 ie the user may pick
question 1 answer = red
and question 3 and answer green
即用户可以选择
question 1 answer = red
和question 3 and answer green
I have to return those personId
's that match that criteria (in the above table it would return a and b) 我必须返回与该条件匹配的
personId
(在上表中它将返回a和b)
psuedo: select from questionanswer table all personId's where question=1 && answer=red AND those personId's where question=3 and answer was green
This code would run after the administrator selects 'search' returning back distinct a and b personId's 该代码将在管理员选择“搜索”并返回不同的a和b personId后运行。
(seems simple but i must be missing something?) (似乎很简单,但是我一定要缺少一些东西吗?)
How are you passing in the QuestionIds and Responses? 您如何传递QuestionIds和Responses? Let's assume you eventually get them into a table variable:
假设您最终将它们放入表变量中:
DECLARE @Search TABLE
( questionId int,
response varchar(30) )
Then your SQL then becomes: 然后,您的SQL将变为:
SELECT q.personID
FROM questionanswertable AS q
INNER JOIN @Search AS s
ON s.questionId = q.questionId
AND s.response = q.response
GROUP BY q.personID
HAVING COUNT(1) = (SELECT COUNT(1) FROM @Search)
SELECT DISTINCT personID
FROM questionanswertable
WHERE (questionID = 1 AND response = 'red')
OR (questionID = 3 AND response = 'green')
SELECT DISTINCT personID
FROM questionanswertable
WHERE questionID = 3 AND response = 'green' AND personID in (
SELECT DISTINCT personID
FROM questionanswertable
WHERE (questionID = 1 AND response = 'red'))
SELECT DISTINCT personId
FROM questionanswer
WHERE questionId IN(SELECT questionId FROM questionanswer WHERE questionId = 1 AND response = 'red')
AND questionId IN(SELECT questionId FROM questionanswer WHERE questionId = 3 AND response = 'green')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.