Reputation: 27685
This query always returns at least one row even if none is found
(
SELECT accounting.time, enclosure.enc_id_, enclosure.txt, accounting.amount AS sum, SUM(ROUND(vatcode.percent/(100+vatcode.percent)*accounting.amount)) AS sum_vat
FROM accounting
INNER JOIN enclosure ON enclosure.id=accounting.enc_id
LEFT JOIN vatcode ON vatcode.id=accounting.vatcode_id
WHERE accounting.account_id='10'
)
UNION (
SELECT accounting.time, enclosure.enc_id_, enclosure.txt, accounting.amount*-1 AS sum, NULL AS sum_vat
FROM accounting
INNER JOIN enclosure ON enclosure.id=accounting.enc_id
WHERE accounting.accountoff_id='10'
) ORDER BY time
I know that the error occurs in the second select here ... , NULL AS sum_vat
.. If I remove it I get an error about not having the same statements in both select? How can this be solved?
return
Array
(
[time] => 0
[enc_id_] => 0
[txt] =>
[sum] => 0
[sum_vat] =>
)
Upvotes: 1
Views: 1877
Reputation: 238078
If you use an aggregate without a group by, the aggregate will run over the entire table, always returning a single row. For example,
select max(price) from items where group = 'Servers'
returns a single row with the highest price. MySQL is the only database that allows other columns without a group by
:
select name, max(price) from items where group = 'Servers'
But confusingly, it would just put a random value in name column; the name here won't be the name of the highest priced server.
In your case, the obvious solution is to add a group by
to the first part of the union:
SELECT accounting.time, enclosure.enc_id_, enclosure.txt, accounting.amount sum,
SUM(ROUND(vatcode.percent/(100+vatcode.percent)*accounting.amount)) sum_vat
FROM accounting
INNER JOIN enclosure ON enclosure.id=accounting.enc_id
LEFT JOIN vatcode ON vatcode.id=accounting.vatcode_id
WHERE accounting.account_id='10'
GROUP BY accounting.time, enclosure.enc_id_, enclosure.txt, accounting.amount
Upvotes: 3