MySQL联合不适用于insert和select语句

时间:2019-03-01 12:17:08

标签: mysql insert mariadb union

我想制作一个SQL脚本以从多个表中获取数据并将其插入一个表中

下面的子查询运行正常

  1. INSERT 语句
  2. 中逐一运行它们时
  3. 当我在插入查询中不使用选择查询时,两个选择查询都可以与并用正常工作。

但是当我使用 UNION 使其成为单个脚本时,它会给我syntax error

INSERT INTO cfx_subscriptions ( cfx_account_id, isv_company_id, license_qty, `status`, created_on, 
subscription_start_date, subscription_end_date, subscription_id, modified_on, product_id) 
(
    SELECT s.idp_account_id, '', 1 AS quantity,
    (CASE 
        WHEN s.activation_status = 1 THEN 'active' 
        WHEN s.activation_status = 2 THEN 'suspended' 
        WHEN s.activation_status = 3 THEN 'deleted' 
        ELSE ''
    END) AS 'status', CAST(FROM_UNIXTIME( s.creation_date / 1000) AS DATETIME ) AS created_on,
    CAST(FROM_UNIXTIME( s.creation_date / 1000) AS DATETIME ) AS subscription_start_date, 
    s.expiry_date, s.sage_company_id, s.updated_date, s.portal_product_id FROM cfx_sage_subscriptions s 
UNION   
SELECT os.idp_account_id, c.id, os.quantity, os.`status`, cast(os.creationDate as DATETIME) AS created_on, 
    cast(os.effectiveStartDate as DATETIME) AS subscription_start_date, cast(os.commitmentEndDate as DATETIME) AS commitmentEndDate,
    os.subscriptionId, cast(os.creationDate as DATETIME) AS modified_on, TRIM(LEADING '0' FROM SUBSTR(os.cloudselect_product_id,4))
        FROM cfx_office365_customer_order_subscriptions  os
        JOIN cfx_office365_customer c ON os.tenantId=c.companyProfile_tenantId

)

下面是上面第一个脚本产生的错误

  

SQL错误(1064):您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册,以在'UNION

附近使用正确的语法

1 个答案:

答案 0 :(得分:1)

尝试在选择结果中避免使用别名

INSERT INTO cfx_subscriptions ( cfx_account_id, isv_company_id, license_qty, `status`, created_on, 
subscription_start_date, subscription_end_date, subscription_id, modified_on, product_id) 
    SELECT s.idp_account_id, '', 1 ,
    (CASE 
        WHEN s.activation_status = 1 THEN 'active' 
        WHEN s.activation_status = 2 THEN 'suspended' 
        WHEN s.activation_status = 3 THEN 'deleted' 
        ELSE ''
    END) , CAST(FROM_UNIXTIME( s.creation_date / 1000) AS DATETIME ) ,
    CAST(FROM_UNIXTIME( s.creation_date / 1000) AS DATETIME ) , 
    s.expiry_date, s.sage_company_id, s.updated_date, s.portal_product_id 
    FROM cfx_sage_subscriptions s 
UNION   
SELECT os.idp_account_id, c.id, os.quantity, os.`status`, cast(os.creationDate as DATETIME) , 
    cast(os.effectiveStartDate as DATETIME) , cast(os.commitmentEndDate as DATETIME) ,
    os.subscriptionId, cast(os.creationDate as DATETIME) , TRIM(LEADING '0' FROM SUBSTR(os.cloudselect_product_id,4))
        FROM cfx_office365_customer_order_subscriptions  os
        JOIN cfx_office365_customer c ON os.tenantId=c.companyProfile_tenantId