简体   繁体   中英

advanced SQL query help. need to translate ruby script to SQL query

I am pretty new with SQL and i have to translate this ruby script to SQL because the ruby script is taking WAY too long to run on the server. Here is the ruby script:

orders = Order.find_all_by_state("in_progress"); nil
orders.each do |o|
  if o.line_items.length == 0 and o.created_at > Time.parse("2011-12-14 00:00:00.000000 -08:00") and o.created_at < Time.parse("2011-12-21 00:00:00.000000 -08:00")
    o.adjustments[0].destroy
    o.shipment.destroy
    o.turnaround_time.destroy
    o.checkout.destroy
    o.destroy
  end; nil
end; nil

Anyway, the associations are as follows:

an order has one checkout, shipment, turnaround time, many line_items, and many adjustments (the orders i want to delete only have 1). I want to delete all orders that have no line items and was created within those range of dates (dec 15th-20th). I also want to delete all objects associated with those orders (shipments, turnaround_times, checkouts, adjustments). I am new to SQL and i have absolutely no idea how to do this. I've been looking at SQL documentation but i am really struggling with the syntax for this. If i could get some help, that would be great.

To delete orders without any line items:

delete from order
where order_id not in (select order_id from line_item);

To delete associated objects that (now) don't have an order:

delete from shipment
where order_id not in (select order_id from order);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM