我是数据库新手,需要一些帮助。我的数据库中有一张表,其中包含有关所有事件的信息。例如,有几行,每一行描述一个不同的事件。
现在,我还需要跟踪参加事件的用户。那么我将如何设计呢?我在想,如果有某种方法,每次将新行添加到事件表时,都可以专门为该事件创建一个新表。那可能吗?或者只在主要事件表中添加一列,用逗号或分号或其他东西分隔参加者的姓名是否是个好主意?还是为每个用户制作一个表格更好,每一行都是一个正在参加的事件?
提前致谢。
最佳答案
更好的方法是使用如下内容:
Create table events(
id integer,
<OTHER EVENT DETAILS HERE (i.e. start time, location, duration etc>
primary key (event_id)
);
Create table users(
id integer,
<OTHER USER DETAILS HERE (i.e. name, email, phone etc)>
primary key (user_id)
);
CREATE TABLE event_users(
event_id integer,
user_id integer,
<OTHER USER/EVENT DETAILS HERE (i.e. ticket price paid etc)>
Primary Key (event_id,user_id),
Foreign Key (event_id) REFERENCES events(id),
Foreign Key (user_id) REFERENCES users(id)
);
这样事件可以有 0 个或多个用户参加,用户可以参加 0 个或多个事件,您不需要创建更多表。
您获取数据的方式类似于:
SELECT U.id
FROM User U, UserEvent UE
WHERE U.id = UE.user_id
AND UE.event_id = <event id you want to search for>;
关于mysql - 让SQL自动建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28017211/