查询总是返回一个空行?

时间:2012-01-22 23:02:07

标签: mysql sql

即使找不到任何行,此查询也始终至少返回一行

(
    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

我知道错误发生在第二个选择... , NULL AS sum_vat ..如果我删除它,我得到一个错误,关于两个选择中没有相同的语句?怎么解决这个问题?

返回

Array
(
    [time] => 0
    [enc_id_] => 0
    [txt] => 
    [sum] => 0
    [sum_vat] => 
)

1 个答案:

答案 0 :(得分:3)

如果您使用没有group by的聚合,则聚合将在整个表上运行,始终返回单行。例如,

select max(price) from items where group = 'Servers'

返回价格最高的单行。 MySQL是唯一允许没有group by的其他列的数据库:

select name, max(price) from items where group = 'Servers'

但令人困惑的是,它只会在名称列中添加一个随机值;这里的名称不是最高价服务器的名称。

在您的情况下,显而易见的解决方案是在联合的第一部分添加group by

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