在MySQL查询中的IF别名上添加WHERE条件

时间:2016-09-17 20:34:38

标签: mysql sql conditional

我在以下查询中为别名is_paidis_overdueis_outstanding添加条件时遇到问题:

SELECT r.doc_number,
       r.doc_date,
       r.due_date,
       r.currency,
       r.amount,
       r.vat,
       r.vatammount,
       (r.amount + r.vatammount) final_amount,
       r.currency,
       b.boq_id,
       b.boq_comp_id,
       b.boq_client_id,
       b.boq_agency,
       b.boq_date,
       b.boq_orders,
       b.receivable_id,
       c.comp_name,
       crm.`cn-name-first`,
       crm.`cn-name-last`,
       bi.inv_path,

  (SELECT SUM(amount_recieved)
   FROM receivables_payments
   WHERE r_id = b.receivable_id) total_amount_received,
       IF (r.amount + r.vatammount =
             (SELECT SUM(amount_recieved)
              FROM receivables_payments
              WHERE r_id = b.receivable_id),
           '1',
           '0') AS is_paid,
          IF (CURRENT_DATE >= r.due_date
              AND r.amount + r.vatammount !=
                (SELECT SUM(amount_recieved)
                 FROM receivables_payments
                 WHERE r_id = b.receivable_id),
                  '1',
                  '0') AS is_overdue,
             IF (r.due_date < CURRENT_DATE
                 AND r.amount + r.vatammount !=
                   (SELECT SUM(amount_recieved)
                    FROM receivables_payments
                    WHERE r_id = b.receivable_id),
                     '1',
                     '0') AS is_outstanding
FROM receivables r
LEFT JOIN boq b ON b.receivable_id = r.id
LEFT JOIN boq_invoices bi ON bi.inv_boq_id = b.boq_id
LEFT JOIN comp_companies c ON c.comp_id = b.boq_comp_id
LEFT JOIN crm_contacts crm ON crm.contact_id = b.boq_client_id
WHERE r.status = 'active'
  AND r.doc_type = 'inv'
  AND b.boq_status = 'active'
  AND is_paid = '1'
ORDER BY r.doc_date DESC LIMIT 10

有没有办法修改此查询并可以在这三个别名上添加条件?

1 个答案:

答案 0 :(得分:1)

在不允许的情况下使用别名。因为。不可能

根据指定的顺序评估查询代码..从WHERE开始 SELECT子句,最后是python tools/dev/v8gen.py x64.release和列别名所以..当执行where时,查询中没有列别名

您可以尝试使用条件因为查询结果而不是原始行值...(这可能会对性能产生影响..因为执行了所有查询并且只过滤了结果具有)