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

倖福魔咒の 提交于 2019-11-26 04:21:25

问题


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?


回答1:


You simply have to do:

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



回答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;



回答3:


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



回答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`



回答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;


来源:https://stackoverflow.com/questions/5907206/mysql-insert-into-tbl-select-from-another-table-and-some-default-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!