Jump to content

Primary key and foreign key


Go to solution Solved by ingerNorway,

Recommended Posts

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 3


Attachment: my sql file exportet from phpmyadmin
Link to comment
https://forums.phpfreaks.com/topic/283146-primary-key-and-foreign-key/
Share on other sites

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?

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.

  • Solution

We just started all over again and used this: 
 

CREATE TABLE fag
(
fagkode VARCHAR (8) 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 :)
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.