I am a sophomore computer science student at a university. I’m making a online app with php/mySQL. This is my first experience with both PHP and mySQL. Anyway I am making an app that keeps track of baseball games. The user creates a team of players and starts a game against another team, the user enters in outcomes while the app scores the game and keeps player stats. I am designing the database and was hoping someone could clarify for me:
Primary Key-
I am pretty sure I understand what this is. Basically its the unique identifier of each row, used for distinguishing each row.
Foreign Key-
Right now I have a “Players” table, I also have a “PlayerStats” table. If I understand it correctly (which I probably don’t) the “Players” table has a column “playerStatsId” which is the primary key of the “PlayerStats” table. This works because there would only be one stats table per player.
No key???- Ok so heres my example. Each user of my app should have the ability to add as many teams as they want to the database. They can only edit the games of a team that they “own”. I was thinking I could accomplish this by having a table with two columns: “username” and “teamId”. Then I could search through the table and pick out the teams that belong to a certain user. I don’t feel like this is the answer because it doesn’t seem very efficient. Is there a better way?
I am grateful for any help! Thank you!!
The player table should have it’s PK in the PlayersStats table as a FK. You could relate it either way, but it makes more sense to have an aspect of the player be the foreign key side of the relationship.
As far as “no key”, you should try to avoid this. In a relational database, if there’s a relationship, you should make that explicit. You avoid having orphan rows this way. An orphan row will basically be a piece of data that, through no relationship, can just sit forever and clutter your Db. In this case, your User table should have a PK and that PK should be what links it to the Teams table. You can have two columns, but one of them should relate to the user table. Your Team table should have a PK acting as a FK in any player’s table as well, as those players belong to teams.
I would also Key the Team table as well. You should never assume a database is ever finished, even if it’s your own. Write code/databases with the intention that they will expand.
There is a lot more to this, I am sure. But these are some general points to get you started.
EDIT:
Seeing the comment in your question: if users can have multiple teams, you may want to have a table between the user and team table with the UserId and TeamId as FK’s. This may be a table you don’t have to key as deleting a user or team should cascade (or error) through that linking table.
So: