mysql - Insert INTO MySQL FROM 另一个表

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

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

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

我做错了什么?

最佳答案

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

关于mysql - Insert INTO MySQL FROM 另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10236932/

相关文章:

mysql - 从现有数据生成缺失数据

mysql - JOIN 语句中的多个 "ON"如何工作

android - 从 android 向 mysql 插入值

mysql - 数据库设计-自定义属性表- "relate"实体表

php - 为网站创建智能预测搜索

java - 想从数据库中检索 java 中 xml 标记的值

mysql - Perl 支持 Mac 错误

mysql - 防止ZF中的Sql注入(inject)

java - jdbc ODBC 连接

php - MySQL 加入案例语句