gpt4 book ai didi

mysql - 优化复杂的SQL查询

转载 作者:行者123 更新时间:2023-11-29 05:02:58 26 4
gpt4 key购买 nike

抱歉,如果这很明显,但我不擅长 SQL。我有几个表都需要连接,但其中一列可以为空。

我有这个问题:

select orders.ordnum, orders.tstamp, orders.sku, code, redeemed_order_num, null as redeemed_date, null as fullname
from customer_subscriptions orders
join bulk_codes codes
on codes.bulk_order_id = orders.subscription_id
where (orders.sku="bulk-box" or orders.sku="bulk-book") and redeemed_order_num is null
union
select orders.ordnum, orders.tstamp, orders.sku, code, redeemed_order_num, redeemed_orders.date redeemed_date, customers.fullname
from customer_subscriptions orders
join bulk_codes codes
on codes.bulk_order_id = orders.subscription_id
join customer_subscriptions redeemed_orders
on codes.redeemed_order_num = redeemed_orders.ordnum
join customers
on customers.cid = redeemed_orders.cid
where (orders.sku="bulk-box" or orders.sku="bulk-book")

顶部选择返回前 9 行,底部选择返回一行。

结果: Screenshot of results

有什么办法可以优化吗?

完整架构在这里:https://pastebin.com/FXGLetcV

最佳答案

我认为你只需要left join:

SELECT orders.ordnum, orders.tstamp, orders.sku, code,
redeemed_order_num, redeemed_orders.date redeemed_date, customers.fullname
FROM customer_subscriptions orders JOIN
bulk_codes codes
ON codes.bulk_order_id = orders.subscription_id LEFT JOIN
customer_subscriptions redeemed_orders
ON codes.redeemed_order_num = redeemed_orders.ordnum LEFT JOIN
customers
ON customers.cid = redeemed_orders.cid
WHERE orders.sku IN ('bulk-box', 'bulk-book')

关于mysql - 优化复杂的SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54472391/

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