I’m a newbie to mysql. I knew this is a very basic question, but I could not figure out how 🙁 ?
My initial attempt:
CREATE TABLE Node(
Id INT( 3 ),
Position VARCHAR( 12 ),
FoodTax INT( 2 ),
HasTreasureMap TINYINT( 1 ),
CurrentPlayer Player,
PRIMARY KEY( Id )
);
In this case, ‘Player’ is another table that I want to add. How can I do this?
You can not add Tables inside tables, what you do is add a foreign key reference, which is basically the ID (or whatever the PRIMARY KEY is) of the other table and make the other table separately.
Note that
INDEX( CurrentPlayer )in the first table is not necessary unless you are going to join the tables, or use theCurrentPlayerfield to search or sort on.If you are using the InnoDB database engine, then you can directly specify the nature of the relationship between the tables within the definition for the
Nodetable as follows.The
FOREIGN KEYaddition causes a few effects, it adds a check in so that you can not set a value forCurrentPlayerin theNodetable that does not already exist in thePlayertable, anyINSERT/UPDATEattempting this would fail. Also, the two optionsON UPDATEandON DELETEtell the database that if a record fromPlayeris updated or deleted, then perform an action automatically via a trigger on theNodetable.ON UPDATE CASCADEmeans that if theIdof aPlayerrecord was updated to something else, it would cascade in to theNodetable, changing that value too.ON DELETE SET NULLstates that if a record is deleted from thePlayertable, then correspondingCurrentPlayervalues inNodeshould be set toNULL.