假设我有三张桌子:
User Table
{
UserId INT,
Username NVARCHAR
...
}
Questions
{
QuestionId INT
QuestionText NVARCHAR
}
Answers
{
AnswerId INT,
QuestionId INT,
UserId INT,
Answer NVARCHAR
}
这个结构显然被过度简化了,但是对于这个例子来说它应该足够了。
例如,选择对特定问题有特定答案的用户的最佳方法是什么 - 假设表格中填充了以下数据:
用户表
UserId Username ...
--------------------------------------------------------------------------------------------------------
1 User1 ...
2 User2 ...
3 User3 ...
4 User4 ...
5 User5 ...
6 User6 ...
7 User7 ...
8 User8 ...
9 User9 ...
10 User10 ...
... ... ...
etc
问题表
QuestionId QuestionText
--------------------------------------------------------------------------------------------------------
1 What is your favorite color?
2 What do you prefer cats or dogs?
3 Do you prefer if it is too hot or too cold?
4 What is your favorite season (Summer, Autumn (Fall), Winter, Spring)?
5 How Old Are you?
... ...
etc
答案表
AnswerId QuestionId UserId Answer
--------------------------------------------------------------------------------------------------------
1 1 1 Red
2 1 2 Red
3 1 3 Blue
4 1 4 Green
5 1 5 Black
6 2 6 Cats
7 2 1 Dogs
8 3 1 Too Cold
9 4 1 Spring
10 5 1 22
11 2 4 Dogs
12 3 4 Too Hot
13 3 3 Too Cold
14 5 6 46
15 1 8 Purple
如果我想选择喜欢狗和红色或紫色以及 50 岁以下等的用户
最好(最有效)的方法是从用户表到答案表有多个连接(每个所需的答案条件一个)
例如:
如果我想获得喜欢狗和红色的用户,我可以使用以下 MSSQL:
SELECT *
FROM
Users
JOIN Answers As a1
ON Users.UserId = a1.UserId
JOIN Answers as a2
ON Users.UserId = a2.UserId
WHERE
(
a1.QuestionId = 1 AND
a1.Answer = 'Red'
) AND
(
a2.QuestionId = 2 AND
a2.Answer = 'Dogs'
)
可能有许多答案条件。
基本上,我要问的问题是编写查询的最佳方法是什么,在该查询中,您对来自同一个表的多行具有相同的列有条件......
抱歉,如果这令人困惑,请随时提出任何问题,我会尽力回答他们......
谢谢。