Shamoon
Shamoon

Reputation: 43639

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

What am I doing wrong?

Upvotes: 11

Views: 18926

Answers (3)

Ryan
Ryan

Reputation: 28247

The VALUES part of the query is not necessary. 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;

Upvotes: 2

Taryn
Taryn

Reputation: 247870

Since you are selecting from a table then you will want to use an INSERT INTO SELECT FROM query:

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. If you wanted to use INSERT INTO VALUES then your query would be like this:

INSERT INTO campaign_ledger 
(
    `campaign_id`
    , `description`
    , amount
    , balance
    , timestamp
)
VALUES
(
    1
    , 'test'
    , 100.00
    , 1000.00
    , NOW()
)

Upvotes: 19

RolandoMySQLDBA
RolandoMySQLDBA

Reputation: 44373

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;

Upvotes: 2

Related Questions