我想制作一个SQL脚本以从多个表中获取数据并将其插入一个表中
下面的子查询运行正常
但是当我使用 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
附近使用正确的语法
答案 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