简体   繁体   English

查询总是返回一个空行?

[英]Query always returns one empty row?

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? 我知道错误发生在第二个选择中... , NULL AS sum_vat ..如果删除它,我会收到关于两个选择中没有相同语句的错误? How can this be solved? 如何解决呢?

return 返回

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

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 : MySQL是唯一一个允许其他列不带group by数据库:

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

But confusingly, it would just put a random value in name column; 但是令人困惑的是,它只会在name列中放置一个随机值; 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: 在您的情况下,显而易见的解决方案是在联合的第一部分添加一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM