7
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)

这是我的语法,但我收到一条错误消息:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 2 行的“SELECT id as campaign_id、“Ported from campaign”作为描述、budget_remaini 附近使用

我究竟做错了什么?

4

3 回答 3

13

由于您是从表中选择,因此您将需要使用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

INSERT INTO VALUES在您使用特定值而不是从表中选择时使用。如果您想使用,INSERT INTO VALUES那么您的查询将是这样的:

INSERT INTO campaign_ledger 
(
    `campaign_id`
    , `description`
    , amount
    , balance
    , timestamp
)
VALUES
(
    1
    , 'test'
    , 100.00
    , 1000.00
    , NOW()
)
于 2012-04-19T21:20:36.797 回答
2
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;
于 2012-04-19T21:20:28.263 回答
2

查询的VALUES部分不是必需的。例如:

 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;
于 2012-04-19T21:21:43.683 回答