Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert INTO MySQL FROM another table

Tags:

mysql

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?

like image 622
Shamoon Avatar asked Apr 19 '12 21:04

Shamoon


2 Answers

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()
)
like image 80
Taryn Avatar answered Oct 09 '22 10:10

Taryn


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;
like image 38
RolandoMySQLDBA Avatar answered Oct 09 '22 11:10

RolandoMySQLDBA