Insert multiple rows with fields from select [duplicate] - mysql

I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?

Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...

Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci

Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid

Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).

We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;

The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid

Related

Insert data in mysql from multiple sources

I want to insert values from different sources. For example
insert into a (('id','name','add'),'college')
select from b where id = 1,'abc'
Here there is no timestamp field in table b
I would rewrite your query as follows:
insert into a (id, name, add, college)
select id, name, add, 'abc' from b where id = 1
With this query, the 4th column in a will be assigned a constant value of 'abc'.

Return Select Query Of Insert Statement MySql

Consider this simple query
Query
INSERT INTO NewCourses (name, location, gid) from
SELECT name, location, 1
FROM courses
which does nothing but insert all records from table courses to table NewCourses .
But if I would like to return this same select statement what will I do?
Without this I need to run this insert statement then again run the same select statement like
INSERT INTO NewCourses (name, location, gid) from
SELECT name, location, 1
FROM courses
//THIS IS THE WASTE OF TIME
SELECT name, location, 1
FROM courses
Please let me know if it is possible?

mysql insert record without using 'values'

INSERT INTO class
(name, description, personid)
Select name, description, 12 from Class where PersonID = 3;
Select * from Class
Select * from Person
Why is the values words is missing from above statement? I thought it should be like this insert into tableA('name') values('select name from tableB') ?
INSERT INTO my_table VALUES ()
Insert data one Table to another table
OR
Not Using Value keyword
Insert into Table2 (Name , Address , Mobile) Select Column 1, Column 2 , Column 3 From Table1
There are different techniques of INSERT, the code above is inserting values from the table itself and change only the personid to 12, he use select so that he can copy the data aside from hardcoded personid . that's why you didn't see the VALUES keyword , but that's true.. the basic insert statement we learn from school is INSERT INTO TableName (Col1, Col2... etc) VALUES (Value1, Value2... etc) , INSERTION of data depends on the requirements that you are working on.

INSERT INTO with SubQuery MySQL

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.

INSERT with SELECT

I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid