用于保存数组的 SQL 结构?

发布于 2024-11-30 15:55:52 字数 157 浏览 0 评论 0原文

如何将一个表与另一个表中的多条记录关联起来?

基本上,我有一个“事件”表,如何跟踪哪些“用户”(在他们自己的单独表中)处于特定事件中?现在,我在“事件”表中只有一列,其中包含已加入该“事件”的用户 ID 的逗号分隔列表。

一定有更好的方法来做到这一点......对吧?

How can I relate a table with multiple records from another table?

Basically, I have a table for an 'event', how do I keep track of which 'users' (in their own seperate table) are in a particular event? Right now I just have a column in the 'event' table with a comma separated list of the users IDs who have joined that 'event'.

There must be a better way to do this...right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梅窗月明清似水 2024-12-07 15:55:52

通常,您有一个名为 users_in_event 的表,该表为与 events 表建立多对多关系的每个用户保存一行。因此,对于每个事件,您将有许多表行单独映射到用户。

CREATE TABLE users_in_event
( 
  user_id INT,
  event_id INT,
  FOREIGN KEY user_id REFERENCES users (user_id) ON UPDATE CASCADE,       
  FOREIGN KEY event_id REFERENCES events (event_id) ON UPDATE CASCADE
  -- Optionally, use ON DELETE CASCADE for the events foreign key
  -- FOREIGN KEY event_id REFERENCES events (event_id) ON UPDATE CASCADE ON DELETE CASCADE
)

要找出哪些用户参与了活动,请执行以下操作:

SELECT 
  users_in_event.user_id,
  users.name
FROM users JOIN users_in_event ON users.user_id = users_in_event.user_id
WHERE event_id=1234;

Typically you have a table called users_in_event which holds one row for each user in a many-to-many relationship with the events table. So for each event, you will have a number of table rows mapped individually to users.

CREATE TABLE users_in_event
( 
  user_id INT,
  event_id INT,
  FOREIGN KEY user_id REFERENCES users (user_id) ON UPDATE CASCADE,       
  FOREIGN KEY event_id REFERENCES events (event_id) ON UPDATE CASCADE
  -- Optionally, use ON DELETE CASCADE for the events foreign key
  -- FOREIGN KEY event_id REFERENCES events (event_id) ON UPDATE CASCADE ON DELETE CASCADE
)

To find out which users are in an event, do:

SELECT 
  users_in_event.user_id,
  users.name
FROM users JOIN users_in_event ON users.user_id = users_in_event.user_id
WHERE event_id=1234;
心安伴我暖 2024-12-07 15:55:52

如果您具有多对多关系,即用户可以参加许多事件,并且事件可以由许多用户参加,那么传统上会用映射表来表示,该映射表具有每个表的主键以及任何特定的属性用户与事件的关系。

例如,如果 USEREVENT 表中的 ID 列均为 INT 类型:

CREATE TABLE USER_EVENT_MAPPING
(
    USER_ID INT,
    EVENT_ID INT
)

If you have a many-to-many relationship, that is, users can attend many events, and events can be attended by many users, that would traditionally be represented with a mapping table with the primary key from each table, plus any attributes specific to the user-event relationship.

For example, if you have ID columns in your USER and EVENT tables that are both type INT:

CREATE TABLE USER_EVENT_MAPPING
(
    USER_ID INT,
    EVENT_ID INT
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文