dimanche 27 septembre 2015

How to manage a list of foreign keys in a table?

I am using Sqlite3.

I have a table, 'Team', which has a nullable list of 'Player's.

Each 'Player' is a unique id which is a foreign key to another table 'Player'.

Each 'Team' can have a max of 10 'Player's.

Each 'Player' is named like this:

"CREATE TABLE IF NOT EXISTS "
"Team"
"("
"TeamID varchar(64) PRIMARY KEY,"
"UserID varchar(64) NOT NULL,"
"League varchar(255) NOT NULL,"
"PlayerID_1 varchar(64),"
"PlayerID_2 varchar(64),"
"PlayerID_3 varchar(64),"
"PlayerID_4 varchar(64),"
"PlayerID_5 varchar(64),"
"PlayerID_6 varchar(64),"
"PlayerID_7 varchar(64),"
"PlayerID_8 varchar(64),"
"PlayerID_9 varchar(64),"
"PlayerID_10 varchar(64),"
"FOREIGN KEY (UserID) REFERENCES User(UserID),"
"FOREIGN KEY (PlayerID_1) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_2) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_3) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_4) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_5) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_6) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_7) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_8) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_9) REFERENCES Player(PlayerID),"
"FOREIGN KEY (PlayerID_10) REFERENCES Player(PlayerID)"
");";

My question is, how can I easily insert a new 'Player' into the table? I need a way to iterate over each current 'Player' in the table, to find the first NULL column.

I am interfacing with this db from C, and it wouldn't be so hard to get the table into memory with a query, iterate over it in memory to find the first NULL 'Player', and insert the new one there, but that seems extremely inefficient!

Also, if this is design is bad, please feel free to propose a better one! I am still pretty new to db design.

Aucun commentaire:

Enregistrer un commentaire