I understand how to do an insert into when all the input data is known, and I know how to do an insert into when all the data is dependent on a select, but I can't find how to do the in between. Where I'm at now:
INSERT INTO takes (stu_id, "CS-001", 1, "Autumn", 2009, null)
VALUES (SELECT id AS stu_id
FROM student
WHERE dept_name = "Comp. Sci.")
Thus I know all the other input data except the student's id, however MySQL just gives me a syntax error.
INSERT INTO takes (stu_id, col2, col3, col4, col5, col6)
SELECT id, 'CS-001', 1, 'Autumn', 2009, null
FROM student
WHERE dept_name = 'Comp. Sci.'
I don't know your destination column names - you have to replace them with the real ones in the query above.
Insert queries can be structured like this:
insert into table
(field1, field2, etc)
(value1, value2 etc)
or like this:
insert into table
(field1, field2, etc)
select this, that, etc
from etc
You tried to combine the two. That's one of the reasons you got an error.
juergen's answer is an example of the 2nd construct. His this and that is a combination of fields and constant values. That's perfectly ok. If you are getting syntax errors, it's in your details. His answer shows the right general idea.
It's often worthwhile to build your query step by step. Start with this:
insert into takes
(stu_id)
select id
from student
where dept_name = 'Comp. Sci'
If that works, add one field inside the brackets and whatever is appropriate to the select clause of your query. Keep going with these baby steps until you get it right. It's an approach I often take.
Related
Part of my job requires that I insert hundreds of fields into a table each week, and I'm getting honestly tired of doing it by hand. SQL is not my forte, so I was wondering if there could be a way to do it semi-automatically?
The query I need to fulfill is:
insert into [table] ([c1][c2][c3][c4][c5][c6])
values([v1][v2][v3][v4][v5][v6]);
Only v1 and v2 need to change each loop, 3 to 6 are always the same value. Could I somehow make an array for the values of v1 and v2 and make it so the query repeats itself advancing through those arrays? Or something that would save me an hour of manually replacing hundreds of values?
Thanks!
MySQL supports a syntax for INSERT INTO ... SELECT ... queries, which may do everything you want in one query.
Example: assuming you have two columns which always get the same string value (col1 + col2) and two columns with values from somewhere else:
INSERT INTO target_table
(col1, col2, col3, col4)
SELECT 'foo', 'bar', id, price
FROM source_table WHERE created_at > '2022-01-01';
That would insert the two static values "foo" and "bar" for each row, plus the values from id and price in source_table.
I need to create an identical copy of many records in a table. The table has a PK id, which of course will be different, in the freshly-copied records.
For example, let's say i have a scrum_card table, with the following non-unique columns: name, description, board_id
I have a dynamic array of id's of records, which i wish to duplicate: [34,56,32,3445,...]
How do i tell MYSQL, to fetch the data from all those records, and make a batch-insert of those same records?
In "human" syntax it would look something like this: "Select all columns(besides id) from scrum_card where the id's are [array of id's], then duplicate each found record".
Use INSERT INTO ... SELECT... and in the list of columns do not include the id:
insert into scrum_card(name, description, board_id)
select name, description, board_id
from scrum_card
where id in (34,56,32,3445,...)
You can use INSERT using a SELECT result set as the source, instead of a set of literal row tuples with VALUES(...).
INSERT INTO new_table (id, col1, col2, col3...)
SELECT NULL, col1, col2, col3...
FROM old_table
WHERE id IN (34,56,32,3445,...)
Using NULL in place of the id column in the SELECT will return NULL for each row, which will cause new_table to generate a new id value.
But SQL does not have any way to do a wildcard like "all columns except id," besides you typing the column names in.
I need to read data from one table and insert into multiple rows in another table in a MySQL database.
Table 1 looks like:
ID, name, e-mail, phone, city, ..., ....
In Table 2 I need to insert data like:
(row1) ID, "name", name
(row2) ID, "e-mail, e-mail
(row3) ID, "phone", phone
...
...
Table 1 has about 3000 rows
I guess I need to use some kind of foreach or do..while but can't find anything that works.
Can anyone give me a clue how to do this?
If I understand your question correctly, you are wanting to do a query on table1 that returns multiple rows, and then insert those into table2 in a single loop. That's the INSERT INTO SELECT statement:
INSERT INTO table2
(name, email, phone)
SELECT name, email, phone
FROM table1;
It can be modified to grab specific results as well:
INSERT INTO table2
(name, email, phone)
SELECT name, email, phone
FROM table1
WHERE name = 'target person';
More information can be found at http://dev.mysql.com/doc/refman/5.7/en/insert-select.html and http://www.w3schools.com/sql/sql_insert_into_select.asp.
EDIT:
Based on your comment, it sounds like you're trying to do this:
SQL split values to multiple rows.
I can't think of a situation where you'd actually want to do that, as you can access all of the data in your existing table as is, and it seems to be bad practice to split data in the way you're requesting. However, the solutions in the above thread should be applicable to what you're trying to do.
Ultimately, you may want to look at how you're actually retrieving the data. Modifying that code would be a better idea :)
Just do a simple INSERT INTO SELECT with group by "id". Here for each id it will insert a new record.
INSERT INTO table2 (name, email, phone)
SELECT name, email, phone FROM table1 GROUP BY id;
Just an update on how I did do this. Since I don't have full access to the database server, I can just add/remove data and create new tables, it was not possible to create a function as suggested in the link provided in the answer.
Instead of trying to loop through the data I did an INSERT for each new row like:
INSERT INTO table2 (id,col2,col3)
SELECT id,'name',name FROM table1;
INSERT INTO table2 (id,col2,col3)
SELECT id,'email',email FROM table1;
Thanks again for the help provided.
I want to insert data from a table WorkTableA to another table TableA, without duplicating the data (i.e. do not insert into WorkTableA if the customer name already exists).
Is there a way of doing it through VBA code.
The field name and their properties in both tables are identical.
What you need is an INSERT INTO statement
INSERT INTO WorkTableA
( CustomerName, Col2, Col3...)
SELECT CustomerName, Col2, Col3
FROM TableA LEFT JOIN WaorkTableA ON TableA.CustomerName = WORKTABLEA.CustomerName
WHERE WorkTableA.CustomerName IS NULL
Something like this might work.
The SELECT part of the statement will select only the ones that DO NOT EXIST in WorkTableA
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.