Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,266 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. :) :)