database - How should I design my relational tables?
问题描述
I am curious to the practicality of structuring my database. Imagine I want to conduct a survey, asking a group of students what are their top 3 preferences out of 10 options. The objective is to find out ranking of the 10 options by looking at the count of students' choices.
Initially, my thought process is to create the following relational tables.
CREATE TABLE person (
personID BIGSERIAL NOT NULL PRIMARY KEY,
personName VARCHAR(50));
CREATE TABLE preference (
preferenceID BIGSERIAL NOT NULL PRIMARY KEY,
personID INT REFERENCES person(personID),
preference1 VARCHAR(50),
preference2 VARCHAR(50),
preference3 VARCHAR(50));
But I begin to stumble on achieving my objective. Since the count of each preference has to be considered in all 3 columns, my current solution is to then manipulate my data (using Excel) until I have the following table:
CREATE TABLE preferenceV2 (
personID INT,
preference VARCHAR(50));
Here, personID
is no longer PK nor is it unique, and preference
can be either of the 10 options. Now, I can achieve my objective by counting the number of votes for each preference and rank them accordingly (through use of PowerBI for example).
However, I realised I end up not leveraging on relational database and the process of manipulating into table preferenceV2
is manual and prone to errors. What should be the best way for me to approach this?
解决方案
你应该有:
CREATE TABLE preferences (
preferenceID BIGSERIAL NOT NULL PRIMARY KEY,
personID INT REFERENCES person(personID),
preference VARCHAR(50)
因此,如果一个人有 3 种偏好,您将拥有
preferenceID personID preference
1 1 A
2 1 B
3 1 C
4 2 B
5 2 C
6 2 D
在这种情况下,你可以做
SELECT preference, COUNT(preference)
FROM preferences
GROUP BY preference
推荐阅读
- python - 将熊猫数据框导出到 sql 服务器时如何修复 ProgrammingError?
- c# - 如何修复:无法连接到任何指定的 MySQL 端口
- html - 仅在 Dreamweaver 中工作的外部 CSS 样式表
- python - 如何使用来自两个不同熊猫数据框的数据创建列散点图
- bash - 如何检查嵌套 if 是否不等于 0 bash
- higher-order-functions - 使用 Hooks 反应功能性 HOC 组件,复制静态方法
- android - 当在堆栈中替换活动时,使用 adb 确定导航事件
- python-3.x - 如何更新数据存储区命名空间中的实体
- java - AdoptOpenJDK 11 如何与 Eclipse Oxygen 和 JavaFX 11 一起工作
- python - 如何使用 Python 测试卷积定理?