ALTER TABLE with new column that is foreign key MYSQL

0

I need to add a new column in one of my tables, but this column in turn is a foreign key from another table but I do not know how to do it ...

I tried this but evidently gave me an error:

ALTER TABLE ordenes ADD COLUMN ticket varchar(50) FOREIGN KEY (ticket) REFERENCES tickets(ticket)
    
asked by Pavlo B. 07.11.2016 в 17:07
source

2 answers

3

First add only the column and then the fk:

ALTER TABLE ordenes ADD ticket VARCHAR(50) NOT NULL;
ALTER TABLE ordenes ADD CONSTRAINT fk_ticket FOREIGN KEY (ticket) REFERENCES tickets(ticket);

In the table tickets it would be better to call it "something" + id instead of "ticket". Remember that it has to be a unique field.

    
answered by 07.11.2016 / 17:13
source
2

The syntax you are using is not supported by mysql. Add the column and the constraint separately, this will work in the vast majority of engines, not just MySQL:

ALTER TABLE ordenes ADD COLUMN ticket varchar(50);
ALTER TABLE ordenes ADD constraint FK_Ordenes_Tickets FOREIGN KEY (ticket) REFERENCES tickets(ticket)

I have added a name to the constraint, but you could skip that part.

    
answered by 07.11.2016 в 17:12