ingerNorway Posted October 21, 2013 Share Posted October 21, 2013 Hi!Trying to add foreign key to tables, but it doesn't work. The SQL question I used is : ALTER TABLE Klasse ADD FOREIGN KEY klassekode REFERENCES Student(klassekode)Get this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'REFERENCES Student(klassekode)' at line 3Attachment: my sql file exportet from phpmyadmin Quote Link to comment https://forums.phpfreaks.com/topic/283146-primary-key-and-foreign-key/ Share on other sites More sharing options...
Barand Posted October 21, 2013 Share Posted October 21, 2013 Foreign keys require InnoDB tables. If yours are MyIsam then it won't work. Quote Link to comment https://forums.phpfreaks.com/topic/283146-primary-key-and-foreign-key/#findComment-1454730 Share on other sites More sharing options...
Barand Posted October 21, 2013 Share Posted October 21, 2013 try ALTER TABLE Klasse ADD CONSTRAINT `fk_klassecode` FOREIGN KEY (klassekode) REFERENCES Student(klassekode) but are you sure you don't want to add the FK to student table, referencing the Klasse table's PK? Quote Link to comment https://forums.phpfreaks.com/topic/283146-primary-key-and-foreign-key/#findComment-1454733 Share on other sites More sharing options...
Agilia Posted October 21, 2013 Share Posted October 21, 2013 Når du lager tabellen Klasse, få med at ENGINE=InnoDB på slutten av sql statement. I MariaDB, kan det hende du må endre InnoDB med XtraDB, men i de fleste versjonene er ikke det nødvendig. Ex.: CREATE TABLE Klasse ( -- bla bla bla )ENGINE=InnoDB; Eller, hvis du allerede har deklarert den til Aria, PBXT eller noe annet, så bruker du simpelthen: ALTER TABLE Klasse ENGINE=InnoDB; Det kan være lurt å teste ved å lage en klone først, men hvis det er skoleoppgave tror jeg ikke du har noe å tape på å konvertere det slik. Prøv å kjør koden på nytt, hvis det ikke fungerer skal jeg prøve å hjelpe deg nærmere. Quote Link to comment https://forums.phpfreaks.com/topic/283146-primary-key-and-foreign-key/#findComment-1454738 Share on other sites More sharing options...
Solution ingerNorway Posted October 21, 2013 Author Solution Share Posted October 21, 2013 We just started all over again and used this: CREATE TABLE fag ( fagkode VARCHAR ( NOT NULL, fagnavn VARCHAR (30) NOT NULL, klassekode VARCHAR (5) NOT NULL, PRIMARY KEY (fagkode), FOREIGN KEY (klassekode) REFERENCES Klasse(klassekode) );But, thanks for all help! Maybe I¨ll need it later Quote Link to comment https://forums.phpfreaks.com/topic/283146-primary-key-and-foreign-key/#findComment-1454739 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.