简体   繁体   English

从另一个表插入INTO MySQL

[英]Insert INTO MySQL FROM another table

INSERT INTO campaign_ledger (`campaign_id`, `description`, amount, balance, timestamp)
VALUES (SELECT id as campaign_id, 'Ported from campaigns' as description, budget_remaining as amount, budget_remaining as balance, NOW() as timestamp FROM campaigns)

That's my syntax, but I get an error saying: 这是我的语法,但我收到一个错误说:

You have an error in your SQL syntax; 您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT id as campaign_id, 'Ported from campaigns' as description, budget_remaini' at line 2 查看与您的MySQL服务器版本相对应的手册,以便在“SELECT id as campaign_id”附近使用正确的语法,“从广告系列中移植”作为说明,budget_remaini'在第2行

What am I doing wrong? 我究竟做错了什么?

Since you are selecting from a table then you will want to use an INSERT INTO SELECT FROM query: 由于您从表中进行选择,因此您将需要使用INSERT INTO SELECT FROM查询:

INSERT INTO campaign_ledger 
(
    `campaign_id`
    , `description`
    , amount
    , balance
    , timestamp
)
SELECT 
    id as campaign_id
    , 'Ported from campaigns' as description
    , budget_remaining as amount 
    , budget_remaining as balance
    , NOW() as timestamp 
FROM campaigns

Only use INSERT INTO VALUES when you are using specific values and not selecting from a table. 仅在使用特定值而不从表中选择时才使用INSERT INTO VALUES If you wanted to use INSERT INTO VALUES then your query would be like this: 如果您想使用INSERT INTO VALUES那么您的查询将如下所示:

INSERT INTO campaign_ledger 
(
    `campaign_id`
    , `description`
    , amount
    , balance
    , timestamp
)
VALUES
(
    1
    , 'test'
    , 100.00
    , 1000.00
    , NOW()
)
INSERT INTO campaign_ledger (`campaign_id`, `description`, amount, balance, timestamp)
SELECT id as campaign_id, 'Ported from campaigns' as description,
budget_remaining as amount,budget_remaining as balance,
NOW() as timestamp FROM campaigns;

The VALUES part of the query is not necessary. 查询的VALUES部分不是必需的。 For example: 例如:

 INSERT INTO campaign_ledger (`campaign_id`, `description`, amount, balance, timestamp)
 SELECT id as campaign_id, 'Ported from campaigns' as description, 
        budget_remaining as amount, budget_remaining as balance, 
        NOW() as timestamp 
 FROM campaigns;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM