优化复杂的SQL查询

时间:2019-02-01 03:17:39

标签: mysql sql join

抱歉,这很明显,但是我不太擅长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

2 个答案:

答案 0 :(得分:2)

我认为您只需要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')

答案 1 :(得分:1)

下面是查询。

         Select orders.ordnum, orders.tstamp, orders.sku, code, redeemed_order_num, null as redeemed_date, null as fullname
           From customer_subscriptions orders
     Inner join bulk_codes codes 
             On codes.bulk_order_id = orders.subscription_id 
            And redeemed_order_num is null -- comment
Left outer join bulk_codes codes 
             On codes.bulk_order_id = orders.subscription_id
left outer join customer_subscriptions redeemed_orders 
             On COALESCE(codes.redeemed_order_num, 111111) = redeemed_orders.ordnum
left outer join customers 
             On customers.cid = redeemed_orders.cid
          where orders.sku='bulk-box' 
             Or orders.sku='bulk-book'

在您给出的查询中,第一个选择将仅连接具有空值的redeemed_order_num,第二个选择中将存在redeemed_order_num上的联接,在联接条件下使用合并或IFNULL函数替换空值