简体   繁体   中英

Best practice MySQL UPDATE/INSERT

Disclaimer: I didn't design these tables, and am aware they're not the best way to store this data. I need advice on the best way to handle the situation.

I have two MySQL tables:

`students`
id        int; primary, unique
prof1_id  varchar 
prof2_id  varchar 
prof3_id  varchar 

`professors`
id         int; primary, unique, auto-increment
username   varchar
fname      varchar
fname      varchar
students_id int
comment    text

A professor's username may be in any of the last three columns in the students table. Professors will need to provide one comment for each student who has them in their row in the students table.

The application that is the front end to this database expects two more columns in the professors table: student_id and comment. Since each student may have any 3 professors in their row, new rows will need to be added to professors whenever they are listed for multiple students. This means that the professors id field will need to auto increment for each new student comment.

What is the best way to accomplish this data transfer with a MySQL query? I've tried looking at UPDATE in combination with JOIN, but I'm not sure there is even a valid way to do this. Also, do I need to create another primary key for professors since the multiple rows will have the same id?

I suspect that a VIEW might be the best way to accomplish this, but the application on the front end expects the information to be stored in the professors table.

One other thing I was considering was that I could create a new table by joining the two tables and have a two-column primary key, students.id, professor.id.

Thanks!

Also, do I need to create another primary key for professors since the multiple rows will have the same id?

Yes. This is good idea.

I wrote simple query that merges data from first table into 2 columns. This is not complete answer, but it can help you a lot:

SELECT id, prof1id as profid
UNION
SELECT id, prof2id
UNION
SELECT id, prof3id
UNION;

You may use this for view, inserts, but im not familiar with specyfic MySQL syntax and i dont want to misslead you. Please give feedback if it work.

"UNION" removes duplicate rows, you may need to use "UNION ALL" to keep duplicates (like duplicated values in 2 or 3 professors columns).

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