简体   繁体   中英

Mysql one to many table

I am making a database for an interpretation company. Each appointment can have only one language and only one interpreter, but interpreters can speak multiple languages. How do I set up the foreign keys?

I've got these tables:

Appointments (fields are start (datetime, primary key), location, subject, language, interpreter)

Language (only field is language (VARCHAR 50), that's the primary key. I didn't use an ID AI number here)

and interpreters (id (int, primary key), first name, last name, email address, language)

The interpreters table is what's throwing me off. I can do a foreign key on Appointments and Interpreters for one language. But I want it so I can have the user add a new appointment and then put the language from the language list, and then select interpreters who can do that specific language. There are interpreters who can do more than one language (eg Spanish and Portuguese and Chinese Mandarin and Chinese Cantonese)

I'm a novice at this stuff and been trying to read about one to many relationships but I'm honestly quite confused.

You need a junction table:

CREATE TABLE interpreter_language (
    interpreter_id INT,
    language VARCHAR(50),
    PRIMARY KEY (interpreter_id, language),
    FOREIGN KEY (interpreter_id) REFERENCES interpreters (id),
    FOREIGN KEY (language) REFERENCES language (language)
);

I would set up the language table so that each language has a unique id (L01 for example).

Column 1 = Language description; Column 2 = Language ID 

Then in the interpreter table each row that exists is a interpreter + language code from the language table.

Column 1 = First name; Column 2 = Last name; Column 3 = Email; Column 4 = language code

In this table you can have multiples of the interpreter but the language is unique per row.

In your appointments table, you indicate the preferred language from the language table. Thus also creating a pool of interpreters that have this code from the interpreter's table.

In this structure think of your language table as a core table, that just feeds a code and a description when the code is called. The tables that need to define a language can only pull from those available in this table. Since a person can speak more than one language, there is no reason why the interpreter's information shouldn't generate multiple times in their respective table.

Example ER Diagram

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM