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服务器版本,以便使用正确的语法 靠近'SELECT id as campaign_id,'从广告系列移植'为 description,budget_remaini'在第2行
我做错了什么?
答案 0 :(得分: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()
)
答案 1 :(得分: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;
答案 2 :(得分: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;