Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Daniel Malek
Daniel Malek
20,140 Points

FOREIGN KEY

I try to understand FOREIGN KEY's. So I created database with 2 tables r_customers and r_cars. With Ttreehouse support I know how to use FOREIGN KEY when 1 customer owns 1 car how I can deal with situation when 1 customer owns 2 cars or 1 car has 2 owners?

Daniel Malek
Daniel Malek
20,140 Points

thats querry I used to create one row:

ALTER TABLE ram_customers ADD COLUMN c_car_1 INTEGER NULL, ADD CONSTRAINT FOREIGN KEY (c_car_1) REFERENCES ram_customers(car_ref_nr);

if I try to do next one

ALTER TABLE ram_customers ADD COLUMN c_car_2 INTEGER NULL, ADD CONSTRAINT FOREIGN KEY (c_car_2) REFERENCES ram_customers(car_ref_nr);

I get an error

1215 - Impossible d'ajouter des contraintes d'index externe

(and I have no idea why is in French :) )

1 Answer

Jeff Lemay
Jeff Lemay
14,268 Points

What you're talking about is a one-to-many relationship but what I think you really want is a many-to-many relationship (where an owner can have multiple cars and the cars can be belong to multiple owners). Check out this link for a pretty good explanation: http://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561 .

Daniel Malek
Daniel Malek
20,140 Points

BIG FAT THANKS for that. Great material and exactly what I need. :) :)