简体   繁体   中英

How to relate user table with a another table

I'm not sure how to ask this question so i couldn't actually google it, but im sure there is an easy answer to this.

I have a Table with users on it and another tables with X amount of rows. what i am looking for is to be able to relate any user to x amount of the rows. At the same time the Rows can have many users related to it, it's both ways

Put a "foreign key" on the other table. Let's say you have a Users table:

Users
----------
ID (int, PK)
Name (varchar)
etc.

Then in your other table you would have a column which points back to this table:

Widgets
----------
ID (int, PK)
UserID (int, FK) <-- this is the foreign key
etc.

The syntax of how you create that foreign key relationship would depend on the database you're using, it'll be in the documentation. There are a variety of options for such a foreign key, but the main thing is that it maintains relational integrity in the data. So if you try to insert a record into Widgets with an invalid UserID then it will throw an error, because there must be a matching ID in Users to relate the data.

Once this relationship is in place, querying the data is simple:

SELECT * FROM Users
INNER JOIN Widgets
  ON Users.ID = Widgets.UserID

Edit: Based on the comment below, it sounds like you're looking for a "many to many" relationship. Same concept, all you need is an intermediate table to connect them. Something like this:

Users
----------
ID (int, PK)
Name (varchar)
etc.

Widgets
----------
ID (int, PK)
etc.

UserWidgets
----------
ID (int, PK) <-- optional, the PK could be a composite of the FKs
UserID (int, FK)
WidgetID (int, FK)

Now any User and any Widget can be connected to any number of the other, by way of adding more records to the UserWidgets table. That table holds the relationships themselves, since those relationships are also data.

Querying is just another join:

SELECT * FROM Users
INNER JOIN UserWidgets
  ON Users.ID = UserWidgets.UserID
INNER JOIN Widgets
  ON UserWidgets.WidgetID = Widgets.ID

You are essentially talking about Normalization and you can use a foreign key constraint here to resolve such relationship.

For eg In case of EMP (MANY) and DEPT ( ONE) [ One department has many employees ], you would put a DEPT_ID ( that identifies a department row in DEPT table) as a Foreign key in EMP table.

You could apply similar solution to your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM