使用计算变量的MYSQL查询

时间:2014-03-25 22:55:37

标签: mysql

在下面的MYSQL中,有一种方法可以使用中间变量receivedrefund来计算net,而不是用简写查询形式重新表达它们吗?

SELECT reservations.id as reservationid, `gh`, `gh-br2`, `gh-loft`, `gh-br3`, `mh-br1`, `mh-br2`, `mh-all`,
              `deposit_amnt` + `pet_deposit` AS deposit, pet_fee, damage_insurance, cleaning_fee, deposit_refund_amnt, rental_amnt,
              otherFees, tax_total as tax, beginDate, endDate, rental_total, phoneNum, cellPhoneNum, email, concat(firstName,' ',lastName) AS name,
    (SELECT COALESCE(SUM(amount),0.0) FROM payments WHERE reservation_id = reservations.id AND payments.type = 'received') AS received,
    (SELECT COALESCE(SUM(amount),0.0) FROM payments WHERE reservation_id = reservations.id AND payments.type = 'refunded') AS refund,
    (SELECT COALESCE(SUM(amount),0.0) FROM payments WHERE reservation_id = reservations.id AND payments.type = 'received') -
    (SELECT COALESCE(SUM(amount),0.0) FROM payments WHERE reservation_id = reservations.id AND payments.type = 'refunded') AS net
    FROM (visitors, reservations)
    WHERE (reservations.visitorCode = visitors.id AND reservations.status = 'confirmed') $queryYear $queryCash
    ORDER BY $sortBy $_SESSION[sort_order]

1 个答案:

答案 0 :(得分:1)

你真的可以解决这个问题!首先,了解显式连接语法(使用joinon关键字)。其次,您不需要所有这些子查询。您可以将逻辑移到from子句中。以下是您查询的替代表单:

SELECT r.id as reservationid, `gh`, `gh-br2`, `gh-loft`, `gh-br3`, `mh-br1`, `mh-br2`, `mh-all`,
       (`deposit_amnt` + `pet_deposit`) AS deposit, pet_fee, damage_insurance, cleaning_fee,
       deposit_refund_amnt, rental_amnt,
       otherFees, tax_total as tax, beginDate, endDate, rental_total,
       phoneNum, cellPhoneNum, email, concat(firstName, ' ', lastName) AS name,
       p.received, p.refund, p.net
FROM visitors v join
     reservations r
     on r.visitorCode = v.id left join
     (select reservation_id,
             sum(case when p.type = 'received' then amount else 0 end) as received,
             sum(case when p.type = 'refunded' then amount else 0 end) as refunded,
             (sum(case when p.type = 'received' then amount else 0 end) -
              sum(case when p.type = 'refunded' then amount else 0 end)
             ) as net
      from payments
      group by reservation_id
     ) p
     on p.reservation_id = r.id
WHERE (r.status = 'confirmed') $queryYear $queryCash
ORDER BY $sortBy $_SESSION[sort_order]