SQL PostgreSQL:根据哪个字段为空选择两个字段之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13723301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PostgreSQL: Select one of two fields depending on which is empty
提问by Ozzy
Hello I have a query where I want to select the value of one of two fields depending if one is empty.
您好,我有一个查询,我想根据一个字段是否为空来选择两个字段之一的值。
field1 and field2
I want to select them as complete_field
我想选择它们作为 complete_field
IF field1 is empty, then complete_field is field2
ELSE complete_field is field1
In php it would be done like:
在 php 中,它会这样做:
$complete_field = $field1 == '' ? $field2 : $field1;
How would I do this in PostgreSQL?
我将如何在 PostgreSQL 中做到这一点?
I tried:
我试过:
SELECT
(IF field1 = '' THEN field2 ELSE field1) AS complete_field
FROM
table
But it doesnt work.
但它不起作用。
Please help me :) Thanks
请帮帮我 :) 谢谢
回答by Marcelo Zabani
Use CASE WHEN .. THEN .. ELSE .. END
, e.g.:
使用CASE WHEN .. THEN .. ELSE .. END
,例如:
SELECT
(CASE WHEN (field1 IS NULL OR field1 = '') THEN field2 ELSE field1 END)
FROM table;
Check it out at the official docs.
在官方文档中查看。
回答by dezso
回答by David Aldridge
The ANSI SQL function Coalesce() is what you want.
ANSI SQL 函数 Coalesce() 正是您想要的。
select Coalesce(field1,field2)
from table;