【问题标题】:Storing Users Location Questionnaire Site存储用户位置调查问卷网站
【发布时间】:2026-01-01 02:25:01
【问题描述】:

我正在建立一个网站,其中包含用户填写的调查问卷。目前我的数据库如下所示。

网站问卷包括

  • 25 个问题
  • 用户可以从每个问题中选择 4 到 6 个答案。

问题

  • 我想在用户中添加国家,州/省/市。
  • 我需要将此合并到我的搜索功能中。请参阅下面的 sql 语句。
  • 客户向我提供了一份包含 23 个国家/地区和 750 个州/省以及大约 6000 个城市的列表。

这应该放在我的数据库中吗?我完全迷失了这个?

当前的数据库设计 见小提琴http://sqlfiddle.com/#!6/bf068/1

User_Table 
ID | UserName
0  | Jack
...

User Questionnaire_Questions_Answer
ID | user_id | question_id | answer_id
0  | 0       | 0           | 0
1  | 0       | 1           | 3
...

Questionnaire_Questions
ID | Question
0  | What type of music do you like?
1  | What is your favorite sport ?
...

Questionnaire_Answers
ID | Answer
0  | Rock
1  | Rap
2  | Basketball
3  | Soccer
...

用于搜索的 SQL 语句

根据用户正在寻找的偏好搜索最佳问卷结果,按最高总匹配数排序

SELECT 
User_Table.id,
User_Table.UserName,
COUNT(User_Table.id) as totalMatches

FROM User_Table 
INNER JOIN Questionnaire_Questions_Answer ON User_Table.id = Questionnaire_Questions_Answer.user_ID
INNER JOIN Questionnaire_Questions ON Questionnaire_Questions.id = Questionnaire_Questions_Answer.question_ID
INNER JOIN Questionnaire_Answers on Questionnaire_Answers.id = Questionnaire_Questions_Answer.answer_ID
WHERE

--Q and A Requested to Match
Questionnaire_Questions.id = '0' and Questionnaire_Answers.answer = '0'
OR 
Questionnaire_Questions.id = '1' and Questionnaire_Answers.answer = '3'

GROUP BY User_Table.id
ORDER BY totalMatches DESC

示例结果

ID | Name | totalMatches
0  | Jack | 2 

【问题讨论】:

    标签: sql-server database-design server normalization


    【解决方案1】:

    这样创建位置表:

    create table dbo.location (id int identity,
    country varchar(200),  
    state_province varchar(100),  
    city varchar 100))
    

    当您添加用户时,将位置的 id 添加到用户表中。

    【讨论】: