Many to many relationship between tables - sql

I have the following problem. I have one table Games with unique ID (primary key) and one table Users with unique ID(primary key). The problem is that many users can play one game and one game can be played by many users. I read, that I need one more table to connect the two tables, but I am not sure how to do it. My idea so far is to create another table Games_users where to store gameID and userID both as PK, but I don't know how to continue.

Your approach is correct: You have to create a bridge table between the two entities related many-to-many and put the GameId and UserId.
Remember also to set the foreign keys in order to keep consistency in your database

Related

How to properly create a many-to-many relationship in an SQL database?

I was recently given an interview question where I was told there is a File table and a Category table. A file (primary key file_id) can have many categories (primary key category_id), and there can be many files. However, there should only be one entry of a file and one entry of a category in their respective tables. Create a schema.
My solution was to create a junction table with file_id and category_id foreign keys. If a user wants to retrieve all the categories of a file, the query would look something like:
SELECT * FROM Files JOIN FileCategory USING (file_id)
Is this solution correct or is there a better way of going about this?
Your solution is correct. The standard way to implement a many-to-many relation between two entities is to create a third entity with a compound primary key consisting of the keys of the two references tables.

SQL tables design layout

I'm trying to design my database with very basic tables and I am confused on the CORRECT way to do it.
I've attached a picture of the main info, and I'm not quite sure how to link them. Meaning what should be a foreign key, or should some of these tables include of LIST<> of the other tables.
UPDATE TO TABLES
As per your requirements, You are right about the associative table
Client can have multiple accounts And Accounts can have multiple clients
Then, Many (Client) to Many (Account)
So, Create an associate table to break the many to many relationship first. Then join it that way
Account can have only one Manager
Which means One(Manager) to Many(Accounts)
So, add an attribute called ManagerID in Accounts
Account can have many traedetail
Which means One(Accounts) to Many(TradeDetails)
So, add an attribute called AccountID in TradeDetails
Depends on whether you are looking to have a normalized database or some other type of design paradigm. I recommend doing some reading on the concepts of database normalization and referential integrity.
What I would do is make tables that have a 1 to 1 relationship such as account/manager into a single table (unless you can think of a really good reason not to). Add Clientid as a foreign key to Account. Add AccountID as a foreign key to TradeDetail. You are basically setting up everything as 1 to many relationships where the table that has 1 record for the id has the field as a primary key and the table that has many has it as a foreign key.

Laravel 3 - Cascade deletes on many to many relationships

I can't seem to work this out at the moment.
I have 3 tables, interests, interest_user, and users, with a many-to-many relationship setup between them.
If I delete an interest I want to make sure that any records in the pivot table are deleted as well (or else I'm going to run into errors down the line I guess).
Can this be done with $table->foreign() on the interests table (I don't think so because there's no id to reference). Otherwise do I have to loop through all the relationships when the interest is deleted and delete each pivot?
I think I'm going to encounter the same problem on a one-to-many relationship I have
One category has many interests. If I delete a category I don't think I can have a foreign key linked to interests on the category table. I'll also need to cascade a category deletion through to all the interest_user records.
Any guidance would be hugely appreciated as my brain is a little frazzled.
Cheers!
Alex
Many to Many:
According to the Laravel 3 Docs on Foreign Keys, your migration for the pivot table should be:
$table->foreign('user_id')->references('id')->on('users')->on_delete('cascade');
$table->foreign('interest_id')->references('id')->on('interests')->on_delete('cascade');
When you delete either a user or an interest, the rows associated with that user or interested in the pivot table will be deleted.
One to many
If you are dealing with a one-to-many (for example, users and creditcards). on the creditcards table you will have a user_id and to set up foreign key like so:
$table->foreign('user_id')->references('id')->on('users')->on_delete('cascade'); (basically exactly like the many-to-many)
So when you delete the user, the row(s) on the creditcards table associated with that user will be deleted as well.

Is this actually a one-to-many relationship?

I have three tables in my PostgreSQL database:
User - Contains a username and password
MaleProfile - Contains information related to each male user
FemaleProfile - Contains information related to each female user
Initially, instead of having separate MaleProfile and FemaleProfile tables, I had a single Profile table. In that situation, I would have had a one-to-one relationship between the User table and the Profile table. But I've since decided that I really need separate profile tables for men versus women. In this new situation, each record in the User table must map to one and only one record in either the MaleProfile table or the FemaleProfile table (but not both). From the other direction, each record in the MaleProfile table maps to one and only one record in the User table. The same holds true for each FemaleProfile record.
Strictly speaking, the relationship between the User table and each of the profile tables is one to zero-or-one. But are these relationships essentially just one-to-many relationships in the sense that "many" in this case means just zero or one (but not more than one)? If so, would I express them as you would any one-to-many relationship by creating a foreign key column in the MaleProfile table and in the FemaleProfile table, each of which points to the PK column in the User table? Would I need to add any additional constraints to the profile tables to maintain referential integrity?
Thank you.
Just make sure the referencing column in your male/female tables has a uniqueness constraint on it as well as a foreign key constraint. This is a 1-to-1/0 relationship, not 1-to-many.
CREATE TABLE MaleProfile
(UserId INT NOT NULL PRIMARY KEY
REFERENCES "User" (UserId));
I believe that you should put the employeeID number in the profile tables and enforcing a unique constraint in those tables. Although I can't really think of how to keep someone from having both a male and female entry, I believe that this way is the way to go.
Check out https://stackoverflow.com/a/669015/1504882 to see a similar situation to yours, but instead with different types of employees.

Designing an SQL Table and getting it right the first time

I currently working on an issue tracker for my company to help them keep track of problems that arise with the network. I am using C# and SQL.
Each issue has about twenty things we need to keep track of(status, work loss, who created it, who's working on it, etc). I need to attach a list of teams affected by the issue to each entry in my main issue table. The list of teams affected ideally contains some sort of link to a unique table instance, just for that issue, that shows the list of teams affected and what percentage of each teams labs are affected.
So my question is what is the best way to impliment this "link" between an entry into the issue table and a unique table for that issue? Or am I thinking about this problem wrong.
What you are describing is called a "many-to-many" relationship. A team can be affected by many issues, and likewise an issue can affect many teams.
In SQL database design, this sort of relationship requires a third table, one that contains a reference to each of the other two tables. For example:
CREATE TABLE teams (
team_id INTEGER PRIMARY KEY
-- other attributes
);
CREATE TABLE issues (
issue_id INTEGER PRIMARY KEY
-- other attributes
);
CREATE TABLE team_issue (
issue_id INTEGER NOT NULL,
team_id INTEGER NOT NULL,
FOREIGN KEY (issue_id) REFERENCES issues(issue_id),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
PRIMARY KEY (issue_id, team_id)
);
This sounds like a classic many-to-many relationship...
You probably want three tables,
One for issues, with one record (row) per each individual unique issue created...
One for the teams, with one record for each team in your company...
And one table called say, "IssueTeams" or "TeamIssueAssociations" `or "IssueAffectedTeams" to hold the association between the two...
This last table will have one record (row) for each team an issue affects... This table will have a 2-column composite primary key, on the columns IssueId, AND TeamId... Every row will have to have a unique combination of these two values... Each of which is individually a Foreign Key (FK) to the Issue table, and the Team Table, respectively.
For each team, there may be zero to many records in this table, for each issue the team is affected by,
and for each Issue, there may be zero to many records each of which represents a team the issue affects.
If I understand the question correctly I would create....
ISSUE table containing the 20 so so items
TEAM table containing a list of teams.
TEAM_ISSUES table containing the link beteen the two
The TEAM_ISSUES table needs to contain a foriegn key to the ISSUE and TEAM tables (ie it should contain an ISSUE_ID and a TEAM_ID... it therefore acts as an intersection between the two "master" tables. It sounds like this is also the place to put the percentage.
Does that make sense?
There are so many good free open source issue trackers available that you should have pretty good reasons for implementing your own. You could use your time much better in customizing an existing tracker.
We are using Bugtracker.NET in the team I work for. It's been customized quite a bit, but there was no point in developing a system from the beginning. The reason we chose that product was that it runs on .NET and works great with SQL Server, but there are many other alternatives.
We can see those entities in your domain:
The "Issue"
"Teams" affected by that issue, in a certain percentage
So, having identified those two items, you can represent that with two tables, and the relationship between them is another table, that could track the percentage impact too.
Hope this helps.
I wouldn't create a unique table for each issue. I would do something like this
Table: Issue
IssueId primary key
status
workLoss
createdby
etc
Table: Team
TeamID primary key
TeamName
etc
Table: IssueTeam
IssueID (foreign key to issue table)
TeamID (foreign key to team table)
PercentLabsAffected
Unless I'm understanding wrong what you're trying to do, you should not have a unique table for each instance of an issue.
Your database should have three tables: an Issues table, a Teams table, and an IssueTeams joining table. The IssueTeams table would include foreign keys (i.e. TeamID and IssueID) that reference the respective team in Teams and issue in Issues. So Issue Teams might have records like (Issue1, Team1), (Issue1, Team3). You could keep the affected percentage of each teams' labs in the joining table.
Well, just to be all modern and agile-y, 'getting it right the first time' is less trendy than 'refactorable.' But to work through your model:
You have Issues (heh heh). You have Teams.
An Issue affects many Teams. A Team is affected by many Issues. So just for the basic problem, you seem to have a classic Many:Many relationship. A join table containing two columns, one to Issue PK and one to Team PK takes care of that.
Then you have the question of what % of teams. There's a dynamic aspect to that, of course, so to do it right, you'll need to specify a trigger. But the obvious place to put it is a column in Issue ("Affected_Team_Percentage").
If I understand you correctly, you want to create a new table of teams affected for each issue. Creating tables as part of normal operations rings my relational database design alarm bell. Don't do it!
Instead, use one affected_teams table with a foreign key to the issues table and a foreign key to the teams table. That will do the trick.