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.
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.
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';
Related
I use my SQL for my app.
Say I have a table of all registered users for my app.
say I have users at hand and I want to filter (or select) from my database the only ones that are registered.
For example my data base have user1,user2......user100
and input user set : user3,user5,user10,user999,user2000 so the output of the query will be : user3,user5 and user 10 only.
Thank you in advance
You seem to want in:
select t.*
from t
where user_id in ('user3', 'user5', 'user10', 'user999', 'user2000')
This will return only the matching users.
The format the user is passing these values is very important here. I am assuming that you have different rows of information. If in that case, you could make use of the below code.
Declare #MyTableVar table
(User_ID VARCHAR(32) primary key)
INSERT #MyTableVar VALUES ('user3')
INSERT #MyTableVar VALUES ('user5')
INSERT #MyTableVar VALUES ('user10')
INSERT #MyTableVar VALUES ('user999')
INSERT #MyTableVar VALUES ('user2000')
SELECT *
FROM #MyTableVar
WHERE User_ID NOT IN (SELECT USER_ID FROM database.schema.table_name)
If your user is passing values in the same row you can convert them to multiple rows using CROSS APPLY. Example can be seen here
Kartheek
I have two tables.
basically i want to insert an id and a string into a table
However, id is a foreign key to another table in which customerId is the primary key
Furthermore my parent table has name
What i have, is name and the stringthat i get from a web ui. However, since i dont have the id that match the customerid of name in the parent table, i don't know how to insert it.
i got this so far, which by the way is my silly attempt to work my human logic around this issue:
INSERT INTO `PostDb`(`Offer`)
VALUES ("String") AND PostDb.id
WHERE CustomerDb.id = PostDb.id AND CustomerDb.name = "MyNameThatIHave"
What would work though. is that i do the following:
SELECT PostDb.id
FROM `PostDb` JOIN CustomerDb
WHERE `CustomerId` = CustomerDb.id AND CustomerDb.name = "MyNameThatIHave"
And then use the id that i get in a new insert command like this:
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
VALUES ("THE ID I GOT BEFORE","STRING")
Basically i want to achieve in ONE query, what the two before stated queries does
You can use SELECT to get values for insert:
INSERT INTO `PostDb`(`Offer`, customerid)
SELECT 'Whatever', id FROM customerdb
WHERE name = 'MyNameThatIHave'
Have you tried LAST_INSERT_ID() function which gives you the last inserted ID PK provided that ID is an auto_increment column.
Once you get that, then you can insert in your child table in your FK column along with the rest attributes.
In that case, use a INSERT INTO .. SELECT FROM construct like
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
SELECT PostDb.`CustomerId`, 'Some Value'
FROM `PostDb` JOIN CustomerDb
ON `PostDb`.`CustomerId` = CustomerDb.id
WHERE CustomerDb.name = "MyNameThatIHave";
I have a many to many relationship and am trying to insert a new relationship. At the point I'm doing the insert I don't know the id so would need to look it up. My table structure looks something like this:
**person**
id
name
**film**
id
title
**person_film**
personId
filmId
Given a person's id and a list of film titles (but not their ids) I'm only able to insert these relationships into the person_film table in two steps.
SELECT id FROM film WHERE title="film1" OR title="film2";
Then the results of that can be used in an insert:
INSERT INTO person_film (personId, filmId) VALUES (5, 5),(5, 7);
Is there a way of doing this in a single SQL statement?
You can do it with a subquery:
INSERT INTO person_film (personId, filmId)
SELECT 5, id FROM film
WHERE title IN("film1","film2");
Here the 5 is the personId value and the filmId will be retrieved from the film table.
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO person_film (personId, filmId)
SELECT
/* Literal number values with column aliases */
1 AS fpersonId,
2 AS filmId,
FROM film
WHERE title="film1" OR title="film2";
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2 but in a normal SELECT you'll need the aliases to access the columns returned.
I have two tables, the first has an auto incrementing ID number, I want to use that as custId in the second table.
I am using an insert into the first table with all the basic info, name, address etc. Then in the second table only 3 things, custId, stocknum, and location. How can I write to these two tables kinda of simultaneously since stockNum may have several values, but always attached to one custId. I hope this makes sense even without putting code in here.
You can't insert into multiple tables at the same time. You have two options. You either do two inserts
INSERT INTO table1 (col1, col2) VALUES ('value1',value2);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO table2 (cust_id, stocknum, location) VALUES (LAST_INSERT_ID(), 'value3', 'value4')
Or you can use a post-insert trigger
CREATE TRIGGER table2_auto AFTER INSERT ON `table1`
FOR EACH ROW
BEGIN
INSERT INTO table2 (cust_id, stocknum, location) VALUES (NEW.id, value3, 'value4')
END
Hope this helps.
After inserting in the first table, The identity field or Auto increment field generate an ID
Get this id Refer Here(LAST_INSERT_ID() MySQL)
Then use this id to store value in the other table
I have two table:
Am using this query to populate my marks table with all 'id' in student table:
$module1= "insert into marks (stud_id,moduleID)
select sid, 1
from user_student
where sid not in (
select * from (
select distinct stud_id from marks where moduleID=1
) alias_name
)";
So i need to take all 'sid' from Table student and populate them into table marks my query above does all that. The problem am encountering is that every time i make a change to the data e.g column test1 , new record are inserted again.
If i populate the marks table manually, Can't i have a code that when new data is available in student table, the data is just updated in marks table...
I don't understand some points of your insert query, why insert sid in stud_id if there's a id in student table to relate them?
Maybe solve your problem the creation of a composed unique key to moduleID and stud_id and use a REPLACE in place of INSERT.
But the right way to do it is using a TRIGGER like:
DROP TRIGGER IF EXISTS `student_after_insert`;
CREATE TRIGGER `student_after_insert` AFTER INSERT ON `student`
FOR EACH ROW INSERT INTO marks (stud_id,moduleID)
SELECT NEW.`id`, `modules_table`.`id` FROM `modules_table`;
PS: I suppose you have a table of modules with name modules_table. Change it accordingly.
I haven't understand your question at the best, my tip is:
Make a unique constraint on marks table (up to you is the choice of best constraint rule).
Then use a trigger to make the right insert/update:
Something like that, (hope that syntax is right):
CREATE TRIGGER myTrigger
AFTER INSERT ON students
FOR EACH ROW
BEGIN
// check that insertion doesn't broke the constraint previously define, then
insert into marks (stud_id,moduleID) values (new.sid, 1);
END
Note: NEW is the row that you have as soon inserted/updated on students. Similar you have OLD metarow.