2014-03-25 121 views
0

在下面的MYSQL中是否有一種方法可以使用中間變量receivedrefund來計算net而不是在慢速查詢表單中重新表達它們?使用計算變量的MYSQL查詢

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] 
+0

存在(將其包裝在子查詢中) - 但在性能方面沒有真正的優勢。並且請不要在列名中使用' - ' – Strawberry

回答

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]