gpt4 book ai didi

MySql Union 立即合并到父表 ID

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:41 25 4
gpt4 key购买 nike

提前致谢。

我正在尝试将两个表合并为一个。下面的查询返回我想要的结果。我知道 UNION ALL 将组合多个表。

但我想在其父行之后立即合并两个表行。

SELECT 
temp.transactionId,
temp.amount,
temp.transactionType
FROM
(
(SELECT
sale.transaction_id AS transactionId,
sale.amount AS amount,
'SALE' AS transactionType
FROM
t_sales sale
WHERE
sale.merchant_id = '1'
)

UNION ALL

(SELECT
refund.refund_transaction_id AS transactionId,
refund.amount AS amount,
'REFUND' AS transactionType
FROM
t_refunds refund
WHERE
refund.merchant_id = '1'
)
)
AS temp

上述查询返回 sales 行 结束后的所有 refunds 行。但我需要在每个销售行之后立即显示所有退款行。退款表有销售表 ID(主键)。有什么办法可以实现吗?

最佳答案

这可以通过 id/sale_id 上的 order by 来完成。

试试这个:

SELECT 
temp.transactionId,
temp.amount,
temp.transactionType
FROM
(
(SELECT
sale.transaction_id AS transactionId,
sale.amount AS amount,
'SALE' AS transactionType,
id,
1
FROM
t_sales sale
WHERE
sale.merchant_id = '1'
)

UNION ALL

(SELECT
refund.refund_transaction_id AS transactionId,
refund.amount AS amount,
'REFUND' AS transactionType,
sale_id as id,
2
FROM
t_refunds refund
WHERE
refund.merchant_id = '1'
)
ORDER BY 4,5
)
AS temp

关于MySql Union 立即合并到父表 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36492322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com