问题
I'm working on a project and am trying to grab a key from another table while still grabbing from the values given. For example...
INSERT INTO Essay (student_ID, student_essay) VALUES (`Students.student_ID`, 'I WANNA BE THE VERY BEST');
I need to grab the student_ID from the Students table (otherwise the numbers will be off since student_ID is auto-increment), but I need to be able to insert the value of the essay.
回答1:
You need to use the Max(id)
function.
You can use Max(id) function also it will return max id and you are using auto increment so offcorse it will return last id and that last id you can insert in 2nd table, like:
INSERT INTO Essay (student_ID, student_essay)
VALUES ((SELECT MAX(s_id) from Students), 'I WANNA BE THE VERY BEST');
here is S_id means you need to provide that id which you want to use in Students table.
回答2:
I'm not sure what you want, but probably you only need an INSERT from SELECT.
INSERT INTO Essay (Student_id, Student_essay)
SELECT student_id, ? student_essay
FROM Student
WHERE name = ?;
You can find this in the docs: Insert from select MySQL
Question Marks represent the values that you will send from the application.
This should solve your problem:
INSERT INTO Essay (Student_id, Student_essay)
SELECT student_id, 'I WANNA BE THE VERY BEST' student_essay
FROM Student
WHERE email = 'asdajo@hota.com';
来源:https://stackoverflow.com/questions/36540202/how-do-i-grab-info-from-one-table-while-still-adding-values