Query linking many-to-many relationship over several tables - sql

I am making a quiz-program. In a quiz I have many participants, but on the other hand participants can enter many quizzes (over time). So I have overcome this many-to-many relationship with a linking table. So far I can understand.. now for the difficulty for me: a participant can either be a group, or a single player.
So a quiz has a participant (with a linking table) and this participant is either a group which has several persons, or this participant is a player and only one single person.
table Quiz : PrimaryKey = quiz_id, (name, date,... )
table QuizParticipant : PrimaryKey = quiz_participant_id, quiz_id
table ParticipantGroup : PrimaryKey = quiz_participant_id, group_id
table participantPlayer : PrimaryKey = quiz_participant_id, person_id
The problem for me is: how do I query all participants of a quiz by quiz_id, and preferably sort them by type (group or player)?
Tips on how to google this stuff are usefull as well :)

It's an interesting design decision. The way you proceed can shape your entire application.
My advice is to record the participant type within each occurance of participation. This would be either "GROUP" or "PLAYER" and would define whether the ParticipantID referred to a GroupID or a PlayerID. This will result in the cleanest database design and application logic in the end.
So your tables look like:
Quiz (QuizID,QuizName)
QuizParticipation (ParticipationID, ParticipantType, ParticipantID)
Group (GroupID,GroupName)
GroupMembers(GroupID,PlayerID)
Player(PlayerID,Name)
You might need to make a custom constraint to ensure that duplicates cannot be created within the ParticipantID and ParticipationType combined fields of the QuizParticipation table, or manage the generation of primary keys carefully.

My suggestion is to always link your quizzes to groups (many to many) and treat single players as a group of 1. So your groups are linked to players (also many to many)

If a person can belong to many groups and a group can have many people, that's another many to many relationship. Since you know how to create these linking tables, create one for this relationship.

Related

sql many to many relationship table design

I am learning sql now and practicing the scenarios to design the tables. I have a one scenario where I could not find proper suitable table structure.
The scenarios is as follows, I want to store depedencies user journey in sql. For example, in customer creation journey, we need to create valid sector, language and country codes in the system. Another example, to create a new account (bank account), we need to create the sector, language and country followed by customer.
So far, I could think of following table design, but I am sure this is not good as there is no primary key and not following the normalization standards.
journey
dependent
order
CUSTOMER
SECTOR
0
CUSTOMER
LANGUAGE
1
CUSTOMER
COUNTRY
2
ACCOUNT
CUSTOMER
0
I understand that this is many to many relationship as one journey can have many dependent and one dependent can be associated with multiple journeys. I need help to efficiently design the tables in sql, please can anyone help on this.
You need from the intermediate/join table that should look like this -
Table name - journey_dependent
Coll(Jurney_FK) Coll(Dependent_FK)
journey_id dependent_id
You can check more here - https://www.baeldung.com/jpa-many-to-many#1-modeling-a-many-to-many-relationship
If journey and dependent values are PK in origin tables, you have 2 FK. You can create a composite PK on that table with that 2 columns.
Maybe order need to be in dependent table. If not, there is information on that table : order. So this is not a pur relationship table. So you could optionally had a technical PK column (auto increment) on it.

SQL database structure with two changing properties

Let's assume I am building the backend of a university management software.
I have a users table with the following columns:
id
name
birthday
last_english_grade
last_it_grade
profs table columns:
id
name
birthday
I'd like to have a third table with which I can determine all professors teaching a student.
So I'd like to assign multiple teachers to each student.
Those Professors may change any time.
New students may be added any time too.
What's the best way to achieve this?
The canonical way to do this would be to introduce a third junction table, which exists mainly to relate users to professors:
users_profs (
user_id,
prof_id,
PRIMARY KEY (user_id, prof_id)
)
The primary key of this junction table is the combination of a user and professor ID. Note that this table is fairly lean, and avoids the problem of repeating metadata for a given user or professor. Rather, user/professor information remains in your two original tables, and does not get repeated.

inserting some values in one field

How can I insert many values into one database field?
Is it possible?
I want to make a table for meetings, and invite many persons. So how can I add persons to my meeting table?
You have to choose a many-to-many design. One person can go to many meetings, and many people can go to one meeting.
Meetings table:
- MeetingId (int)
- Date (DateTime)
People table:
- PersonId (int)
- Name (char)
PeopleInMeeting table:
- MeetingId (int)
- PersonId (char)
This way you can book many people in you meeting (with many records in PeopleInMeeting), o one person can book in many meetings (same way)
Entity
In a relational database each table stores a single type of record as row (e.g. a single Meeting, or a single Person, or a single MeetingAttendance). Each record (row) in a table has some columns, a primary-key (e.g. ID) plus different attributes (e.g. name, date, location). This concept is called entity.
Relationship
Since for each type of record there is one table, you can now model the relationships between these records/tables using foreign-keys if its one-to-one (1:1) or one-to-many (1:n). In your case a single person can visit/attend many meeting's and a single meeting can be visited by many persons. So the relationship, lets name it MeetingAttendance, is many-to-many (n:m). This n:m relationship is best modeled using a so called association-table, which stores both foreign-keys.
See similar question Relationships for “Meetings” List.
Entity-Relationship (ER)
An ER-model or ER-diagram depicts these relationships between entities.
So your ER-model will look like this:

How to stablish a one to many relationship between 2 tables

I'm dealing with this situation. I've got three tables in SQL SERVER called Movies, Series and Orders.
Orders has an ItemId where this could be a MovieId (Movies PK) or SerieId (Series PK). I mean, in Orders table could have records where are from movies of series.
I don't know how to maintain this relationship or which could be the best way to implement it. Until I know, I only can create 1 to 1 or 1 to many relationships between 2 tables, not for 3.
Thanks in advance.
In this case I think it would be better to store Movies and Series in the same table with the common attributes incl. a column which indicates the type (Movie or Serie) and then have the additional attributes in seperate tables (if you want to normalize) or even in the same table (in order to avoid joins).
You should learn about implement table inheritance in sql-server.
Do you have a product and this product may be a Movie or a Serie.
In linked sample a person may be a student or a teacher.
The best way is:
create a generic table for movies and series with the fields that both entities should share (like ItemId).
create a table for movies that references the table created on step 1, containing the fields that must be compiled only for movies. This new table will be in relation one-to-one with the previous one.
same thing for series.
create the orders table and set ItemId foreign key to point to the ItemId primary key of the table created on step 1.

Can a many-to-many join table have more than two columns?

I have some tables that benefit from many-to-many tables. For example the team table.
Team member can hold more than one 'position' in the team, all the positions are listed in the position db table. The previous positions held are also stored for this I have a separate table, so I have
member table (containing team details)
positions table (containing positions)
member_to_positions table (id of member and id of position)
member_to_previous_positions (id of member and id of position)
Simple, however the crux comes now that a team member can belong to many teams aghhh.
I already have a team_to_member look-up table.
Now the problem comes how do I tie a position to a team? A member may have been team leader on one team, and is currently team radio man and press officer on a different team. How do I just pull the info per member to show his current position, but also his past history including past teams.
Do I need to add a position_to team table and somehow cross reference that, or can I add the team to the member to positions table?
It's all very confusing, this normalization.
Yes, a many-to-many junction table can have additional attributes (columns).
For example, if there's a table called PassengerFlight table that's keyed by PassengerID and FlightID, there could be a third column showing the status of the given passenger on the given flight. Two different statuses might be "confirmed" and "wait listed", each of them coded somehow.
In addition, there can be ternary relationships, relationships that involve three entities and not just two. These tables are going to have three foreign keys that taken together are the primary key for the relationship table.
It's perfectly legitimate to have a TeamPositionMember table, with the columns
Team_Id
Position_Code
Member_Id
Start_Date
End_Date NULLABLE
And and a surrogate ID column for Primary Key if you want; otherwise it's a 3-field composite Primary Key. (You'll want a uniqueness constraint on this anyway.)
With this arrangement, you can have a team with any set of positions. A team can have zero or more persons per position. A person can fill zero or more positions for zero or more teams.
EDIT:
If you want dates, just revise as shown above, and add Start_Date to the PK to allow the same person to hold the same position at different times.
My first thought:
Give your many-to-many teams/members table an ID column. Every team-to-member relationship now has an ID.
Then create a many-to-many linking positions to team-member relationships.
This way, teams can have multiple members, members can have multiple teams, and members can have multiple positions on a per-team basis.
Now everything is nice and DRY, and all the linking up seems to work. Does that sound right to anyone else?
Sounds like you need a many-to-many positions to teams table now.
Your team_to_member table can indeed have an extra column position_id to describe (or in this case point to) the position the member has within that team.
Get rid of member_to_previous_position table. Just use member_to_positions and have these columns:
MemberToPositionID (autoincrement OK only)
MemberID
PositionID
StartDate
EndDate
Then to find current positions, you do:
select *
from member_to_positions
where EndDate is null