Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql -> insert into tbl (select from another table) and some default values [duplicate]

As the title says, I am trying to insert into one table selecting values from another table and some default values.

INSERT INTO def (catid, title, page, publish)  (SELECT catid, title from abc),'page','yes')   INSERT INTO def (catid, title, page, publish)  VALUES ((SELECT catid, title from abc),'page','yes')) 

The first query gives a mysql error and the second one gives column count does not match.

What do I need to do?

like image 779
wannabeprogrammer Avatar asked May 06 '11 05:05

wannabeprogrammer


People also ask

How can I insert one table from another table in mysql?

In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

How insert into select works?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

How to write insert record query?

It is possible to write the INSERT INTO statement in two ways: 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)


2 Answers

You simply have to do:

INSERT INTO def (catid, title, page, publish)  SELECT catid, title, 'page','yes' from `abc` 
like image 72
Nican Avatar answered Sep 23 '22 03:09

Nican


If you want to insert all the columns then

insert into def select * from abc; 

here the number of columns in def should be equal to abc.

if you want to insert the subsets of columns then

insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;  

if you want to insert some hardcorded values then

insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc; 
like image 25
kanishka vatsa Avatar answered Sep 24 '22 03:09

kanishka vatsa