【发布时间】:2012-03-14 08:17:21
【问题描述】:
如何使用联合和联接优化查询?是否可以在这里将一些联接移到联合之外?
(
SELECT accounting.id, accounting.time, accounting.subaccount_id AS module_id, accounting.balance_invoice_id AS balance_id, accounting.currency_amount*-1 AS currency_amount, accounting.amount*-1 AS amount, enclosure.enc_id_, enclosure.txt, currency.name AS currency_name, IF(balance_invoice.amount, accounting.currency_amount*-1+SUM(balance_invoice.amount), accounting.currency_amount*-1) AS balance
FROM accounting
INNER JOIN enclosure ON enclosure.id=accounting.enc_id
LEFT JOIN currency ON currency.id=accounting.currency_id
LEFT JOIN balance_invoice ON balance_invoice.accounting_id=accounting.id
WHERE accounting.att_booked=1
GROUP BY accounting.id
)
UNION (
SELECT accounting.id, accounting.time, accounting.subaccountoff_id AS module_id, accounting.balanceoff_invoice_id AS balance_id, accounting.currency_amount, accounting.amount, enclosure.enc_id_, enclosure.txt, currency.name AS currency_name, IF(balance_invoice.amountoff, accounting.currency_amount+SUM(balance_invoice.amountoff), accounting.currency_amount) AS balance
FROM accounting
INNER JOIN enclosure ON enclosure.id=accounting.enc_id
LEFT JOIN currency ON currency.id=accounting.currency_id
LEFT JOIN balance_invoice ON balance_invoice.accounting_id=accounting.id
WHERE accounting.att_booked=1 && accounting.type IN (0,1,2)
GROUP BY accounting.id
) ORDER BY time DESC
【问题讨论】:
-
您的查询包含 'GROUP BY accounting.id' 子句和 SELECT 子句中的许多未聚合字段。 MySQL 允许,但不正确;检查一下,也许重写你的查询。