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?


Solution 1:

You simply have to do:

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

Solution 2:

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;

Solution 3:

INSERT INTO def (field_1, field_2, field3) 
VALUES 
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')

Solution 4:

If you you want to copy a sub-set of the source table you can do:

INSERT INTO def (field_1, field_2, field3)

SELECT other_field_1, other_field_2, other_field_3 from `abc`

or to copy ALL fields from the source table to destination table you can do more simply:

INSERT INTO def 
SELECT * from `abc`

Solution 5:

With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW() then you can do something like this:

INSERT INTO course_payment 
SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
FROM orders ORDER BY order_id DESC LIMIT 10;