Topic: Better sql construct in sales/includes/db/sales_order_db.inc

At the end of the file sales/includes/db/sales_order_db.inc we have:

function last_sales_order_detail($order, $field)
{
        $sql = "SELECT $field
            FROM ".TB_PREF."sales_order_details d
            WHERE order_no =
            (SELECT order_no FROM ".TB_PREF."sales_orders o
            WHERE debtor_no=" . db_escape($order->customer_id) . "
            ORDER BY order_no DESC LIMIT 1)
            ORDER BY d.id DESC LIMIT 1";        

        $last_query=db_query($sql, "Could not retrieve last order detail");
        $row = db_fetch_row($last_query);
        return $row == false ? false : $row[0];
}

Kindly change it to:

function last_sales_order_detail($order, $field)
{
        $sql = "SELECT $field
            FROM ".TB_PREF."sales_order_details d
            LEFT JOIN " .TB_PREF."sales_orders o on d.order_no=o.order_no
            WHERE debtor_no=" . db_escape($order->customer_id) . "
            ORDER BY d.id DESC LIMIT 1";

        $last_query=db_query($sql, "Could not retrieve last order detail");
        $row = db_fetch_row($last_query);
        return $row == false ? false : $row[0];
}

It uses a left join instead of a secondary select.

The on d.order_no=o.order_no can become USING (order_no) to further optimise it.

Re: Better sql construct in sales/includes/db/sales_order_db.inc

Thanks

www.boxygen.pk

Re: Better sql construct in sales/includes/db/sales_order_db.inc

This has been pushed to stable repo. Thanks.

Joe

Re: Better sql construct in sales/includes/db/sales_order_db.inc

It doesn't appear to have been pushed into the GitHub repo yet here. but is available in the SF.net repo. Hope the GitHub repo gets synched correctly in time.