我想从一个表中读取所有数据并将一些数据插入到另一个表中。我的查询是
INSERT INTO mt_magazine_subscription (
magazine_subscription_id,
subscription_name,
magazine_id,
status )
VALUES (
(SELECT magazine_subscription_id,
subscription_name,
magazine_id
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC), '1')
但我收到了错误
#1136 - Column count doesn't match value count at row 1
请帮帮我。
答案 0 :(得分:95)
您可以使用INSERT...SELECT语法。请注意,您可以引用' 1'直接在SELECT部分。
INSERT INTO mt_magazine_subscription (
magazine_subscription_id,
subscription_name,
magazine_id,
status )
SELECT magazine_subscription_id,
subscription_name,
magazine_id,
'1'
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC
答案 1 :(得分:18)
如果要将一个表中的所有数据插入到另一个表中,则只需要一个非常简单的sql
INSERT INTO destinationTable (SELECT * FROM sourceDbName.SourceTableName);
答案 2 :(得分:5)
它不会像这样工作。
当您尝试使用查询插入行时,查询中应该包含所有值。
要插入上述问题
magazine_subscription_id, subscription_name, magazine_id, status
在您选择的查询中
magazine_subscription_id, subscription_name, magazine_id, status
1这是不可能的。
如果要插入,则需要使用直接值查询
进行插入答案 3 :(得分:3)
实际上,从一个表到另一个表的复制数据的mysql查询是
Insert into table2_name (column_names) select column_name from table1
其中,值从table1复制到table2
答案 4 :(得分:2)
如果有像“id”这样的主键你必须排除它,例如我的php表有:id,col2,col3,col4列。 id是主键,所以如果我运行此代码:
INSERT INTO php (SELECT * FROM php);
我可能会收到此错误:
#1062 - Duplicate entry '1' for key 'PRIMARY'
所以这是解决方案,我排除了“id”键:
INSERT INTO php ( col2,col3,col4) (SELECT col2,col3,col4 FROM php2);
所以我的新php表已经有了所有php2表行。
答案 5 :(得分:0)
试试这个。你做错了。
INSERT INTO mt_magazine_subscription(
magazine_subscription_id,
subscription_name,
magazine_id, status) VALUES (
(SELECT magazine_subscription_id, subscription_name,
magazine_id,1 as status FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC)
)
答案 6 :(得分:0)
INSERT INTO mt_magazine_subscription (
magazine_subscription_id,
subscription_name,
magazine_id,
status )
VALUES (
(SELECT magazine_subscription_id,
subscription_name,
magazine_id,'1' as status
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC))
答案 7 :(得分:0)
INSERT INTO mt_magazine_subscription (
magazine_subscription_id,
subscription_name,
magazine_id,
status )
VALUES (
(SELECT magazine_subscription_id,
subscription_name,
magazine_id,'1' as status
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC));
答案 8 :(得分:-1)
INSERT INTO destination_table (
Field_1,
Field_2,
Field_3)
SELECT Field_1,
Field_2,
Field_3
FROM source_table;
但这是一个不好的MYSQL
请改为:
drop the destination table: DROP DESTINATION_TABLE;
CREATE TABLE DESTINATION_TABLE AS (SELECT * FROM SOURCE_TABLE);
答案 9 :(得分:-2)
INSERT INTO mt_magazine_subscription SELECT *
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC