简体   繁体   English

什么时候在postresql查询中使用COALESCE函数?

[英]When to use COALESCE function in postresql query?

I googled a lot but did not find understandable answer for my question. 我在Google上搜索了很多,但是没有找到可以理解的答案。 It is interesting 4 me when do I have to use COALESCE function in query. 4我何时必须在查询中使用COALESCE函数,这很有趣。 Thank you in advance for your answer. 预先感谢您的答复。

When you want the first non-NULL value for a "column" (column in this sense means in your query output, not your table). 当您想要“列”的第一个非NULL值时(这种意义上的列意味着在查询输出中而不是表中)。

One example might be a company's contact person. 一个示例可能是公司的联系人。 Say you have three columns: 假设您有三列:

CompanyRep
CompanySecretary
CompanyOwner

and you want to store all three. 并且您想存储所有这三个。 But, in a query that lets you know who you should contact, you want to deliver one of those in the order given. 但是,在一个让您知道应该与谁联系的查询中,您想按给定的顺序交付其中之一。 But any or all of them may be NULL. 但是它们中的任何一个或全部可能为NULL。

The query: 查询:

select coalesce (CompanyRep, CompanySecretary, CompanyOwner, '???') as contact
from blah blah blah

would give you the value you want. 会给您您想要的价值。 It will give you the first value it finds that isn't NULL. 它将为您提供发现的第一个非NULL值。 If all the possible table columns are NULL, you'll get '???' 如果所有可能的表列均为NULL,则将得到'???' since that's obviously not NULL. 因为那显然不是 NULL。


Another example, let's say you have an accounting database that has separate columns for debit and credit value - never mind that this is usually a bad design and you should have one column with a sign - let's assume it was set up by someone with less accounting knowledge than me :-) 再举一个例子,假设您有一个会计数据库,该数据库的借方和贷方价值各有不同的列-别介意这通常是一个不好的设计,并且应该有一个带有符号的列-假设它是由会计较少的人设置的比我知识:-)

So, if you then wanted to sum up all transactions to ensure credits and debits are equal, you could use something like: 因此,如果您随后想对所有交易进行汇总以确保贷方和借方相等,则可以使用以下方法:

select sum (coalesce (credit, -debit, 0)) from txns ...

That way, it will select the credit value if it's not NULL, otherwise it will select the negation of the debit value (all values are positive). 这样,如果贷方值不为NULL,它将选择贷方值,否则将选择借方值的取反(所有值均为正)。 If they're both NULL, it will give you zero. 如果它们都为NULL,它将为您提供零。

What happens when they're both non-NULL I hear you ask. 我听到你问,当它们都为非NULL时会发生什么。 Well, that's why it's a bad design :-) 好吧,这就是为什么它的设计不好的原因:-)

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

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