从函数中进行查询

时间:2013-03-20 12:07:16

标签: php mysql function

目前我已经编写了一个函数来检查订单是否完全支付。在该功能中,第二个功能用于确定总订单价格。在第一个函数中,总订单价格与订单的所有交易进行比较,并根据该订单支付订单。

下面提到的功能。我正在寻找的是一种可以将函数更改为单个查询的方法。类似的东西:

SELECT * 
FROM order 
WHERE
  ((Grandtotal - TransactionTotal) <= 0)

以便查询返回例如如果付费则返回true,如果没有支付则返回false。

function IsOrderPaid:

function IsOrderPaid($order_id){
  $returnvalue = false;
  $ordertotal = CalculateOrderTotal($order_id);

  $sql = "SELECT SUM(amount) AS TransactionTotal FROM order_transaction WHERE order_id='".mysql_real_escape_string($order_id)."' AND status='9'";
  $result = mysql_query($sql) or die(mysql_error());
  $row = mysql_fetch_object($result);

  if(($ordertotal - $row->TransactionTotal) <= 0 ){
    $returnvalue = true;
  }

  return $returnvalue;
}

funcion CalculateOrderTotal

function CalculateOrderTotal($order_id){
  $sql = "SELECT
            order_id, SUM(total) GrandTotal
          FROM
            (
            SELECT ordering_id AS order_id, SUM(price * quantity) AS total
            FROM order_products
            WHERE order_id = ".mysql_real_escape_string($order_id)."

            UNION ALL
            SELECT ordering_id AS order_id, SUM(price * quantity * -1) AS total
            FROM  rma_products
            WHERE bestelling_id = ".mysql_real_escape_string($order_id)."

            UNION ALL
            SELECT order_id, amount AS total
            FROM order_shipping
            WHERE order_id = ".mysql_real_escape_string($order_id)."

            UNION ALL
            SELECT order_id, amount AS total
            FROM order_service
            WHERE order_id = ".mysql_real_escape_string($order_id)."

            UNION ALL
            SELECT order_id, SUM(amount * -1) AS total
            FROM order_gift
            WHERE order_id = ".mysql_real_escape_string($order_id)."
          )subTable
          WHERE order_id <> 0
          GROUP BY order_id";
  $result = mysql_query($sql) or die(mysql_error());
  $row = mysql_fetch_object($result);

  return $row->GrandTotal;     
}

我知道mysql_*已被弃用,但这是下一个问题。

1 个答案:

答案 0 :(得分:0)

这似乎是一个SQL问题。看起来您想获得订单的总数,然后减去交易总额以确定他们是否已全额付款。你能做到这一点:

其中$ id =您的订单ID

SELECT 
sum(op.price * op.quantity) as order_products_total,
sum(rma.price * rma.quantity) as rma_total,
FROM order 
left join order_products op on ordering_id = order.order_id 
left join rma_products rma on ordering_id  = order.order_id 
WHERE
order.order_id = $id 

您可以为所有left join表执行此操作(我只将order_products和rma_products作为示例),但您可以对order_shipping和其他表执行相同操作。

在您的PHP中,您将获得所有总计,并且您可以在那里进行比较语句(仅来自一个查询)。