I’m trying to design a database for a little project I am working on in PHP. I don’t have much experience working with databases (as you will soon notice) so right now I’ve thrown myself a little in the deep end.
I’m developing a database that will be the foundation for a basic stats system I am writing in PHP. I have concluded that I will need (at least) 3 tables.
TOURNAMENT – > One tournament has many matches
tournamentID SMALLINT UNSIGNED PRIMARY KEY,
MATCH -> One match has many players
tournamentID SMALLINT UNSIGNED,
matchID SMALLINT UNSIGNED,
PLAYER -> One player has many matches and many tournaments
tournamentID SMALLINT UNSIGNED,
matchID SMALLINT UNSIGNED,
playerID SMALLINT UNSIGNED,
My attempt to create this database:
<?php
//Connect
$link = mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("stats") or die(mysql_error());
//Drop old tables
mysql_query('DROP TABLE PLAYERS');
mysql_query('DROP TABLE MATCHES');
mysql_query('DROP TABLE TOURNAMENT');
echo('Old tables dropped<br \>');
//Create new tables
// TOURNAMENT
mysql_query('CREATE TABLE TOURNAMENT(
tournamentID SMALLINT UNSIGNED PRIMARY KEY,
)') or die(mysql_error());
echo('TOURNAMENT created...<br />');
// MATCHES
mysql_query('CREATE TABLE MATCHES(
tournamentID SMALLINT UNSIGNED,
matchID SMALLINT UNSIGNED,
PRIMARY KEY (tournamentID, matchID),
FOREIGN KEY (tournamentID) REFERENCES TOURNAMENT(tournamentID)
)') or die(mysql_error());
echo('MATCH created...<br />');
// PLAYERS
mysql_query('CREATE TABLE PLAYERS(
tournamentID SMALLINT UNSIGNED,
matchID SMALLINT UNSIGNED,
playerID SMALLINT UNSIGNED,
PRIMARY KEY (tournamentID, matchID),
FOREIGN KEY (tournamentID) REFERENCES TOURNAMENT(tournamentID),
FOREIGN KEY (matchID) REFERENCES MATCHES(matchID)
)') or die(mysql_error());
echo('PLAYERS created...<br />');
echo('Blank tables created');
mysql_close();
When I execute the PHP script I receive err 150, which I think has something to do with my primary keys/foreign key references in the PLAYERS table:
Old tables dropped
TOURNAMENT created...
MATCH created...
Can't create table 'stats.players' (errno: 150)
I have done some reading and looked at some previous questions but I don’t really understand the actual problem (the reason the error is occurring) in the first place. Clearly the design of my database is incorrect but I’m not sure how I should approach improving and fixing it.
Please help.
Barring any problems with table definition that people are commenting on above, the reason you’re getting error 150 is because
Players(obviously the table with the problem) can’t be created because it can’t usematchIDas a foreign key. Why? Because you can only use foreign keys that are a key on the other table.PRIMARY KEY (one, two)does make a unique primary key from these two columns, but onlyonewill be considered a key on its own.You can fix this easily by adding this to
Matches: