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.
Related
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';
I need some help again.
I have to insert two values in a table into "hospital_database". This table has five columns, and it's called "personas". The columns' names are "cod_hospital(PK)", "DNI", "Apellidos", "Funcion" and "Salario"... I have to insert "99887766" and "Martínez Martínez, Alejandro" into "DNI" and "Apellidos", but according to the question, I must to insert into a "hospital" where only there's 1 person...
I have to use "insert+select" and my last effort was this:
insert into personas
values (99887766, 'Martínez Martínez, Alejandro');
select dni, apellidos
from personas
where count(dni)=1;
I tried something like that, and a lot of ways... but It doesn't work like the question asks. I have to use insert+select, so I shouldn't write ";" before "select".
Honestly I'm still guessing at this a little, but maybe you intend to insert an additional row in the personas table if only 1 row exists in that table for a given hospital code. To do this you need to use group by with having:
insert into personas (cod_hospital, dni, apellidos)
select cod_hospital, 99887766, 'Martínez Martínez, Alejandro'
from personas
group by cod_hospital
having count(*)=1
insert have several sintaxis and looks like you are mixing all of them
One is insert values http://www.w3schools.com/sql/sql_insert.asp
INSERT INTO table_name
VALUES (value1,value2,value3,...);
the other insert from a select
http://www.w3schools.com/sql/sql_insert_into_select.asp
INSERT INTO table2
SELECT * FROM table1;
And if you dont include all the field, you have to indicate which fields are you inserting
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
cod_hospital is the table's PK, you could only insert one person per hospital, change your PK to: cod_hospital, dni
INSERT INTO numbers (type, number)
VALUES 'telephone', SELECT DISTINCT tel FROM flat_data
I am attempting to select distinct numbers from one table and then insert them into another table.
However I need to manually set the type column that I am inserting into manually.
I can do it without the DISTINCT but I can't get my head around how to do it with!
INSERT INTO numbers (type, number)
SELECT DISTINCT 'telephone', tel
FROM flat_data
I have a query submitting multiple items in table a.
For example:
insert into a values(id,name) (5,'john'),(6,'smith');
Though I also need to select some third value from other table with this id.
For example:
insert into a values(id,name,money) (5,'john',(select money from b where id=5)),(6,'smith',(select money from b where id=6));
The problem with the above is that it's a bit repetitive and also uses sub selects.
I wonder if it's possible to rewrite this using JOIN, (which should also reassure that there is a relation to the table b on that given id, lest it inserts a NULL).
Any ideas?
You're allowed only one SELECT for each INSERT so you need to re-write this to select multiple rows, not insert multiple values at once. Could you create a temporary table with the two sets of values in it and INSERT those with a JOIN?
CREATE TEMPORARY TABLE _tmp_a (id INT PRIMARY KEY, name VARCHAR(255));
INSERT INTO _tmp_a (5, 'john'), (6, 'smith')
INSERT INTO a (id, name, money) SELECT _tmp_a.id, _tmp_a.name, b.money FROM _tmp_a LEFT JOIN b ON b.id=_tmp_a.id
I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.